csharp 静态方法/字段/类

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了csharp 静态方法/字段/类相关的知识,希望对你有一定的参考价值。

//By prefixing the field with the const keyword, you can declare that a field is static but that its value can never change
//A const field does not use the static keyword in its declaration but is nevertheless static
//example

class Math
{
...
public const double PI = 3.14159265358979323846;
}

//A static class can contain only static members
//A static class cannot contain any instance data or methods
//example

public static class Math
{
public static double Sin(double x) {...}
public static double Cos(double x) {...}
public static double Sqrt(double x) {...}
...
}

//when decalre a method static, then no need to instanciate and object of that class where that method is located
//example of static
//method Sqrt is called from class Math without instanciate an object
public double DistanceTo(Point other)
{
int xDiff = this.x - other.x;
int yDiff = this.y - other.y;
double distance = Math.Sqrt((xDiff * xDiff) + (yDiff * yDiff));
}

//example without static
Math m = new Math();
double d = m.Sqrt(42.24);

以上是关于csharp 静态方法/字段/类的主要内容,如果未能解决你的问题,请参考以下文章

csharp 如何使用静态字段和方法打印递增的数字序列的示例。从计算机编程基础知识

(10)静态方法静态字段静态类匿名类

静态类,静态方法,静态成员

一个类只有静态字段和方法是不好的做法吗?

面向对象类成员之静态字段和普通字段以及普通方法的比较

静态字段和静态方法