两个反射类的问题。

qqq123 2003-01-26 11:26:26
问题1:何时MemberInfo.Declaring和MemberInfo.ReflectionType不相等?
问题2:
public interface AInterface
{
void AMethod();
}
public class AClass:AInterface
{
void AInterface.AMethod()
{
//...
}
}
public class MainApp
{
static public void Main()
{
MethodInfo mi=typeof(AClass).GetMethod("AMethod");
//为何mi为null?
mi=typeof(AClass).GetMethod("AInterface.AMethod");
//为何mi还是为null?
}
}
后来用GetMethodes()方法列出AClass的所有方法,发现没有AMethod的踪迹,这又是为何?

...全文
73 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
qqq123 2003-01-31
  • 打赏
  • 举报
回复
这回我彻底明白了,谢谢,顺便说一声:“祝大家新年快了,来年心想事成(^_^)"
vmstat 2003-01-29
  • 打赏
  • 举报
回复
一个类的member,有的是继承的(包括它的Base class,以及实现的interface),有的是自己定义的。

继承来的member,他们是在Base class或者interface里面所declare,所以当用DelcaringType的时候,所得的结果就是Base Class或者Interface的类,而不是当前的类。

而ReflectedType则就是指当前所操作的对象的类。

不知道这样说清楚没有。

可以自己写个像Saucer写的程序,运行一下,就更容易明白了。
saucer 2003-01-28
  • 打赏
  • 举报
回复
you mean MemberInfo.DeclaringType and MemberInfo.ReflectedType?

when a member is declared in a base class and the current type being reflected is a subclass, for example


using System;
using System.Reflection;

class Base { public void TestMethod(){} }
class Derived : Base {}

class Test
{
static void Main()
{
MemberInfo[] mi = typeof(Derived).GetMember("TestMethod");
Console.WriteLine( mi[0].DeclaringType );
Console.WriteLine( mi[0].ReflectedType );
}
}
qqq123 2003-01-28
  • 打赏
  • 举报
回复
第二个问题我明白了,特别谢谢saucer,lostinet,vmstat,第一个问题更正如下:
问题1:何时MemberInfo.DeclaringType和MemberInfo.ReflectionType不相等?
vmstat 2003-01-27
  • 打赏
  • 举报
回复
1,直接原因是AClass的AMethod不是Public;

2,不是Public的原因是在AClass里面,AMethod不是普通的Interface method implementation,而是所谓的Explicit Interface Member Implementation,因为用了AInterface.AMethod这样的定义;一旦一个Class的Method是Explicit Interface Member Implementation的话,这个Method既不能被定义为Public,也不能定义为Private;

所以

A,将原来AClass中的AMethod定义为 public void AMethod(),后来的mi = typeof(AClass).GetMethod("AMethod") 就能成功了;或者

B,改成 mi = typeof(AInterface).GetMethod("AMethod") 也能成功; 或者

C, 改成 mi = typeof(AClass).GetMethod("AInterface.AMethod", BindingFlags.Instance | BindingFlags.NonPublic) 亦可;
Lostinet 2003-01-26
  • 打赏
  • 举报
回复
1?
public class B
{
public string GetMsg()
{
return "B";
}
}
public class C:B
{
}

用MethodInfo mi=typeof(C).GetMethod("GetMsg");就是。..


2:
public interface M
{
string GetMsg();
}
public class D:M
{
string M.GetMsg()
{
return "D::M.GetMsg";
}
}

foreach(MemberInfo mi in typeof(D).GetMembers(BindingFlags.Instance|BindingFlags.NonPublic))

..
saucer 2003-01-26
  • 打赏
  • 举报
回复
GetMethod (String) searches for the public method with the specified name , try

mi=typeof(AClass).GetMethod("AInterface.AMethod", BindingFlags.Instance | BindingFlags.NonPublic);

17,741

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 .NET Framework
社区管理员
  • .NET Framework社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧