访问类的private或internal成员[转载]

... that access modifiers like public, private and internal are enforced by the language compilers (C#, VB.NET) only and not on IL level?

That means that you can invoke any private or internal member in any class, residing in any assembly, just by using Reflection.

To invoke a private static method Calc from the internal class Calculations in the AssemblyWithPrivateMembers assembly that requires two parameters of type int and returns an int, you can write the following few lines of code.

  Assembly asm = Assembly.Load("AssemblyWithPrivateMembers");

  Type t = asm.GetType("AssemblyWithPrivateMembers.Calculations");

  object[] args = new object[] { 2, 4 };

  BindingFlags bindingFlags = BindingFlags.DeclaredOnly | BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.InvokeMethod;

  int result = (int)(t.InvokeMember("Calc", bindingFlags, null, null, args));

For you as a developer it means that you can use all non-public members you find by browsing the .NET framework base class library (using .NET Reflector for example).

But: Please use this possibility with caution! There will always be a reason why a class or member is not declared public. Additionally you are never sure if the class or member will change in later versions of the assembly.
Form:http://dotnetjunkies.com/WebLog/nenoloje/archive/2004/03/19/9490.aspx

posted @ 2004-03-24 08:49 dudu 阅读(2028) 评论(3)  编辑 收藏 所属分类: C#

  回复  引用  查看    
#1楼 2004-03-24 11:45 | rock      
访问private可以,但是访问internal就不一定了吧。
public class DataGridControl : DataGrid
{
public DataGridControl()
{
MethodInfo mi = this.GetType().GetMethod("get_DataGridRows",BindingFlags.FlattenHierarchy | BindingFlags.IgnoreCase | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static);
}
}
中mi的值为null
DataGridRows是属性,get方法定义为internal DataGridRow[] get_DataGridRows();
但是就是得不到,查MSDN说,能查到public,private,protected的定义的,就是没有提到internal。

那位大侠点拨一下在下,如何调用internal定义的方法。
  回复  引用  查看    
#2楼 2004-03-24 18:05 | Justin Shen      
似乎并不是完全可以访问,记得有一个Attribute是用来标记,是否允许访问私有成员的,但忘记是哪个了...-_-b

访问限制不光是compile层的限制,在IL里也是有 private public的概念的。
  回复  引用    
#3楼 2005-08-02 15:13 | 1 [未注册用户]
this.GetType().GetMethod()
改成

thi.GetType().BaseType.GetMethod()

标题  
姓名  
主页
Email (博主才能看到) 
验证码 *  看不清,换一张 [登录][注册]
内容(请不要发表任何与政治相关的内容)  
  登录  使用高级评论  新用户注册  返回页首  恢复上次提交      


相关链接: