简体   繁体   中英

Why I can't call all Methods from another class?

I try to call a method from another class. I've added the reference and find the class. I'm able to call some methods of this class to but I can't call all of the methods in this class.

The main class is public partial class and the class with the methods I want to use is private static class . The method I try to call is public static . And there is no difference between the methods I can call and the method I can't call. That's the problem I don't understand. Please can someone explain?

namespace MyNamespace2
{
    private static class MyClass
    {
        public static void MyMethod() { }
    }
}

namespace MyNamespace1
{
    class Program
    {
        static void Main(string[] args)
        {
            //can't call
            MyClass.MyMethod();
        }
    }
}

If the class you're trying to access is private it doesn't matter if its methods are public, you can't access the class itself.

Consider it this way. If you're not allowed to enter New York, it doesn't matter if all of the houses are open inside the city, since you can't get into the city itself .

To get back to code however there is a case in which you can access private classes: if the calling function is part of a class that contains your private class.

If you have the freedom to manipulate the code for the class you're trying to access then you should attempt something similar to this:

class A {
  private static class B {
    public static void Foo() {}
  }

  public void Bar() {
    B.Foo();
  }
}

In this code you can call B.Foo() from any member function of A , but not from outside of A .

You've written

i want to use is private static class

Your private class and its methods, properties and fields is not available, even though they have a public modifier itself. You have to read this article

But if you are able to move your private class try this:

class Program
{
    private static class Test
    {
        public static void Foo() { }
    }

    static void Main(string[] args)
    {
        Test.Foo();
    }
}

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