简体   繁体   English

从Java和C#中无法从非静态类访问静态方法

[英]Access static method from non static class possible in java and not in c#

Access static method from non static class with object. 使用对象从非静态类访问静态方法。 It is not possible in C#. 在C#中是不可能的。 Where it is done by JAVA. 由JAVA完成。 How it works? 这个怎么运作?

example of 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();
    }
}

Output of the program: 计划的输出:

This is static method.
This is static method.
This is non static method.

How to do this in C#? 如何在C#中做到这一点? thanks in advance.. 提前致谢..

C# forbids referencing a static method through instance.Method , only Type.Method is acceptable. C#禁止通过instance.Method引用静态方法,仅Type.Method是可接受的。 To call a static method, you need to go through the type, not an instance. 要调用静态方法,您需要遍历类型,而不是实例。
In your case this means that StaticMemberClass.staticDisplay() works, but obj.staticDisplay() does not. 在您的情况下,这意味着StaticMemberClass.staticDisplay()有效,但obj.staticDisplay()无效。


When a method is referenced in a member-access (§7.6.4) of the form EM , 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 . 当以EM形式的成员访问 (第7.6.4节)引用方法时,如果M是静态方法,则E必须表示包含M 的类型 ,并且如果M是实例方法,则E必须表示以下实例:包含M的类型。

(C# Language Specification Version 4.0 - 10.6.2 Static and instance methods) (C#语言规范版本4.0-10.6.2静态方法和实例方法)

When a static member M is referenced in a member-access (§7.6.4) of the form EM , E must denote a type containing M . 在以EM形式的成员访问 (第7.6.4节)中引用静态成员ME必须表示包含M的类型。 It is a compile-time error for E to denote an instance. E表示实例是编译时错误。

(C# Language Specification Version 4.0 - 10.3.7 Static and instance members) (C#语言规范版本4.0-10.3.7静态和实例成员)

You can't. 你不能。 You'll need to use the actual class, in your case 在这种情况下,您需要使用实际的类

StaticMemberClass.staticDisplay();

You could create an instance member to wrap the call to the static member. 您可以创建一个实例成员,以将调用包装到静态成员。 Or make the static member an instance member. 或将静态成员设为实例成员。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM