简体   繁体   中英

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#. Where it is done by JAVA. How it works?

example of 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#? thanks in advance..

C# forbids referencing a static method through instance.Method , only Type.Method is acceptable. 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.


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 .

(C# Language Specification Version 4.0 - 10.6.2 Static and instance methods)

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 . It is a compile-time error for E to denote an instance.

(C# Language Specification Version 4.0 - 10.3.7 Static and instance members)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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