嵌套类的非公共方法的访问

嵌套类的非公共方法的访问

本文介绍了嵌套类的非公共方法的访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以访问嵌套类的非公共方法?我需要限制将特殊类(嵌套类)初始化为嵌套该特殊类的类的功能.

Is it possible to access non-public methods of a nested class? I need to restrict the ability to initialize a special class (the nested class) to the class that the special class in nested in.

推荐答案

public class A
   {
       public A()
       {
           B b1 = B.GetObject();
       }
       public class B
       {
           private B()
           {
           }
           public static B GetObject()
           {
               return new B();
           }
       }
   }



是您需要的吗?



Is it what you needed ?


public B(object caller)
{
   if(caller is A) //or caller is IA (IA is interface)
     throw new NotSupportedException("Object of A is not supported");
}



像这样的东西:thumbsup:



Something like this :thumbsup:


using System.Reflection; 


其次,获取类的类型


Second, get the type of the class

Type t = MyClass.InnerClass.GetType()


第三,尝试使用这种类型(它将收集公共成员和非公共成员的集合)


Third, play around with that type (it will give a collection of public and non-public members)

t.GetMethods()[0].Invoke(this)


我真的不确定确切的语法,但是如果您使用的是Visual Studio,那应该不是问题.


I''m really not sure about the exact syntax but if you''re using Visual Studio, that should not be a problem.


这篇关于嵌套类的非公共方法的访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 17:38