Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
401 views
in Technique[技术] by (71.8m points)

c# - How to do proper Reflection of base Interface methods

I have 2 interfaces and 2 classes that I investigate via Reflection:

  • IParent
  • IChild - derives from IParent
  • Parent
  • Child - derives from Parent

Strange thing for me is the fact that when I look through reflection on IChild type I don't find IParent method.

Same code applied to Child type works as expected - reflection shows Parent method.

interface IParent
{
     void ParentMethod();
}

interface IChild : IParent
{
     void ChildMethod();
}

class Parent 
{
     public void ParentMethod(){}
}

class Child : Parent
{
     public void ChildMethod(){}
}

void Main()
{
    //investigate derived interface
     Type t = typeof(IChild);
     var info = t.GetMethod("ChildMethod");//ok
     Console.WriteLine(info); 
     info = t.GetMethod("ParentMethod");//returns null!
     Console.WriteLine(info); 
     //investigate derived class
     t = typeof(Child);
     info = t.GetMethod("ChildMethod");//ok
     Console.WriteLine(info);
     info = t.GetMethod("ParentMethod");//ok
     Console.WriteLine(info);
}

Please explain such behaviour?

Is there any workaround to reflect base interface's methods from the derived interface's type?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you are dealing with an interface, use

t.GetInterfaces()

then you can check for methods on the types returned above.

Finding interface members by name is not relyable, be mindful that whilst in C# interface members cannot be renamed on implementation, in the CLR the names may be modified. (IDisposable.Dispose() is sometimes renamed to Close). In il there is an instruction called .implements that allows one to change names. I believe VB.Net also has this feature.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...