Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...