2012-02-08 116 views
2

我可以从类的实例访问方法吗?例如:C#类:通过实例访问方法

class myClass 
{ 
     private static int n = 0; 

     public static myClass() 
     { n = 5;} 

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

} 

,并在无效的主要:

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

这给了我:cannon be accessed with an instance referece。是因为我宣布函数是静态的吗?如果是这样,当我应该使用静态,当不是因为在C++中,如果我声明静态它只是初始化一次。这是与C#的情况?

+1

使用'myClass.Afis()'或删除方法声明中的'static'关键字 – yas4891 2012-02-08 09:00:19

+1

请参见[this question](http://stackoverflow.com/questions/2308681/what-is-the-difference-between -a-static-variable-in-c-vs-c)来比较'static'的C++和C#的含义。 – PHeiberg 2012-02-08 09:03:59

回答

3

您需要使用类名称而不是变量名称才能访问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.

1

是 - 当你怀疑 - 你不能通过对象的实例访问静态方法,只能通过类型本身。

换句话说:

myClass.Afis(); 

自然 - 反过来也是真实的;您无法通过该类型访问实例方法。

你可以找到更多关于何时,后无来者,使用static在如this one其他问题,但我要说的是static限制某些可取之类的可测试性和多态性(仅举几个)等不应该成为你的“默认位置”。

1

通过类本身调用静态方法,而不是类的实例。

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

这是正确的 - 这是一个静态的功能,因此被称为像:

myClass.Afis(); 
1

Is it because i declared the function static?

没错。

If that is so when should I use static

猜测什么 - 从错误:当你不需要访问实例变量。

because in c++ if i declare something with static it just initialize once. Is that the case with c#?

如果你的意思是一个静态构造函数 - 是的。

基本上你有什么没有一个“类”,但不能在所有被实例化的静态类。

1

静态方法是谁的方法连接到班级广告不实例。 如果您希望每个实例都可以使用相同的方法,则可以使用此方法。 例如,如果我想统计我使用静态属性的类的实例。 要访问静态方法和属性,您必须使用类的名称而不是实例的名称。

0

您将您的方法标记为静态。因此你必须通过类型访问它。

当方法引用类型并且不使用实例信息时,使用静态方法。 String.IsNullOrEmpty(string s)就是这样一种静态的方法。它属于字符串类,但不需要实例环境。尽管每个对象从对象继承的方法ToString()都需要一个实例上下文来定义表示为字符串的内容。