嵌套类的非公共方法的访问 [英] Acessing non-public methods of nested class

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

问题描述

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

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.

推荐答案


我需要限制初始化特殊类的能力"

您只能使用私有构造函数来做到这一点.在您的情况下,它将是单例模式.

What does it mean by
"I need to restrict the ability to initialize a special class"

You can only do so using a private constructor. It will be a singleton pattern in your case.

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 ?


如果只需要一组类型的特定类型,则可以在构造函数中发送该类型.

If you want only a specific type of a family of types, you can send the type in the constructor.

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:


是的,实际上,您可以通过反射来做所有事情.首先,放置
Yes, actually you could do everything with reflection. First, place
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.


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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆