c# - 从非静态类访问静态方法可能在 java 而不是在 c# 中

标签 c# static static-methods static-classes

从带有对象的非静态类访问静态方法。 这在 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, if M is a static method, E must denote a type containing M, and if M is an instance method, E must denote an instance of a type containing M.

(C# 语言规范版本 4.0 - 10.6.2 静态和实例方法)

When a static member M is referenced in a member-access (§7.6.4) of the form E.M, E must denote a type containing M. It is a compile-time error for E to denote an instance.

(C# 语言规范版本 4.0 - 10.3.7 静态和实例成员)

关于c# - 从非静态类访问静态方法可能在 java 而不是在 c# 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12436148/

相关文章:

java - 是否建议使用静态变量来维护状态?

c# - 如何将 char 和 char* 从 C# 传递到 C++/CLI?

c# - 如何清理 Entity Framework 对象上下文?

android - 通过静态方法访问 SharedPreferences

c++ - 为什么要创建一个带有静态 shared_ptr 返回成员的对象?

php - 如何强制执行 protected 静态函数

PHP:变量名作为类实例

c# - C# 中的 'out' 修饰符

c# - 返回符号的函数

JAVA:多个类中的静态字段+公共(public)接口(interface)