从带有对象的非静态类访问静态方法。 这在 C# 中是不可能的。由JAVA完成的地方。 它是如何工作的?
java的例子
/**
* Access static member of the class through object.
*/
import java.io.*;
class StaticMemberClass {
// Declare a static method.
public static void staticDisplay() {
System.out.println("This is static method.");
}
// Declare a non static method.
public void nonStaticDisplay() {
System.out.println("This is non static method.");
}
}
class StaticAccessByObject {
public static void main(String[] args) throws IOException {
// call a static member only by class name.
StaticMemberClass.staticDisplay();
// Create object of StaticMemberClass class.
StaticMemberClass obj = new StaticMemberClass();
// call a static member only by object.
obj.staticDisplay();
// accessing non static method through object.
obj.nonStaticDisplay();
}
}
程序输出:
This is static method.
This is static method.
This is non static method.
如何在 C# 中执行此操作? 提前致谢..
最佳答案
C# 禁止通过instance.Method
引用静态方法,只有Type.Method
是可以接受的。要调用静态方法,您需要遍历类型,而不是实例。
在您的情况下,这意味着 StaticMemberClass.staticDisplay()
有效,但 obj.staticDisplay()
无效。
When a method is referenced in a member-access (§7.6.4) of the form
E.M
, ifM
is a static method,E
must denote a type containingM
, and ifM
is an instance method,E
must denote an instance of a type containingM
.
(C# 语言规范版本 4.0 - 10.6.2 静态和实例方法)
When a static member
M
is referenced in a member-access (§7.6.4) of the formE.M
,E
must denote a type containingM
. It is a compile-time error forE
to denote an instance.
(C# 语言规范版本 4.0 - 10.3.7 静态和实例成员)
关于c# - 从非静态类访问静态方法可能在 java 而不是在 c# 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12436148/