类的受保护成员的反映
using System;
using System.Reflection;
namespace Reflection
{
class Test
{
protected void methodname()
{
Console.WriteLine(("in the world of the reflection"));
Console.Read();
}
}
class Program
{
static void Main(string[] args)
{
// BindingFlags eFlags = BindingFlags.Default | BindingFlags.Instance | BindingFlags.Public|BindingFlags.NonPublic;
BindingFlags eFlags = BindingFlags.Instance|BindingFlags.NonPublic;
Test aTest = new Test();
MethodInfo mInfoMethod = typeof(Reflection.Test).GetMethod("methodname", eFlags);
mInfoMethod.Invoke(aTest, null);
}
}
}
根据 msdn BindingFlags.Nonpublic 用于访问非私有成员。如果我仅使用此枚举,Get 方法将返回 null 值。但如果使用枚举 - 实例和非公共,则调用所需的方法。这两者有什么区别呢。当我必须使用实例和公共/非公共组合时。
using System;
using System.Reflection;
namespace Reflection
{
class Test
{
protected void methodname()
{
Console.WriteLine(("in the world of the reflection"));
Console.Read();
}
}
class Program
{
static void Main(string[] args)
{
// BindingFlags eFlags = BindingFlags.Default | BindingFlags.Instance | BindingFlags.Public|BindingFlags.NonPublic;
BindingFlags eFlags = BindingFlags.Instance|BindingFlags.NonPublic;
Test aTest = new Test();
MethodInfo mInfoMethod = typeof(Reflection.Test).GetMethod("methodname", eFlags);
mInfoMethod.Invoke(aTest, null);
}
}
}
As per the msdn BindingFlags.Nonpublic is used to access the non private members. If I use only this enum the Getmethod returns null value. But if use the enum - Instance and nonpublic the required method is called. What is the difference between these two. When I have to use instance and public/nonpublic combination.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
根据
GetMethod()
的文档:Instance
/Static
和Public
/NonPublic
指定两个不同的内容,您必须指定两者才能获得结果。Per the documentation of
GetMethod()
:Instance
/Static
andPublic
/NonPublic
specify two different things and you have to specify both in order to get the result.如果不指定枚举,则使用默认值。如果这样做,则必须指定两者:
(请参阅 http://msdn.microsoft.com/en-us/library/system.reflection.bindingflags.aspx)
If you don't specify the enum, the default is used. If you do, you have to specify both:
(See the note in the remarks section on http://msdn.microsoft.com/en-us/library/system.reflection.bindingflags.aspx)