C# 类 : Accesing methods through instances

标签 c# static

我可以从类的实例访问方法吗?示例:

class myClass
{
       private static int n = 0;

       public static myClass()
       { n = 5;}

       public static void Afis()
       { 
              Console.WriteLine(n);
       }

}

在空白 Main 中:

static void Main()
{
          myClass m = new myClass();
          m.Afis();
}

这给了我:cannon be accessed with an instance referece。是因为我声明函数是静态的吗?如果是这样,我什么时候应该使用 static,什么时候不应该,因为在 C++ 中,如果我用 static 声明一些东西,它只初始化一次。 c#也是这样吗?

最佳答案

您需要使用类名而不是变量名来访问static 方法。

myClass.Afis();

我已将链接附加到 Static Classes and Static Class Members编程指南,如您所问,何时应该使用它们以及何时不使用它们。

编程指南的一点努力:

A static class can be used as a convenient container for sets of methods that just operate on input parameters and do not have to get or set any internal instance fields. For example, in the .NET Framework Class Library, the static System.Math class contains methods that perform mathematical operations, without any requirement to store or retrieve data that is unique to a particular instance of the Math class.

关于C# 类 : Accesing methods through instances,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9190209/

相关文章:

c# - C# 中的静态类

c++ - 如何捕获初始化静态成员时抛出的异常

c# - Geolocator.RequestAccessAsync 方法

c# - 文本前面的 Visual Studio 修饰会干扰选择

c# - 要选择的 Entity Framework 查询

c# - 使用 IValueConverter 验证可为 null int

c# - 如何合并 3 个关节并将图像叠加到其上,以便图像旋转

c++ - 在 C++ 中定义 float 的静态数组

c++ - 不能在 c++ 类实现文件 (.cpp) 中的静态方法上使用 "static"关键字

c - 如何以及在何处调用外部定义的结构