How do I retrieve a reference to a subobject using Reflection in C#?

南楼画角 提交于 2019-12-24 13:35:32

问题


I'm trying to use duck typing using reflection in C#. I have an object of some random type and I want to find if it implements an interface with a specific name and if it does - retrieve a reference to that interface subobject so that I can later read (get) a property value via that interface.

Effectively I need as using Reflection.

The first part is easy

var interfaceOfInterest =
   randomObject.GetType().GetInterface("Full.Interface.Name.Here");

which will either retrieve the interface description or null. Let's assume it's not null.

So now I have an object reference to an object that surely implements that interface.

How do I have the "cast" like retrieval of the subobject using Reflection only?


回答1:


You don't need to, simply access the properties of the interface, through the interface type, but whenever you need to pass an instance, simply pass the original object instance.

Here is a LINQPad program that demonstrates:

void Main()
{
    var c = new C();
    // TODO: Check if C implements I
    var i = typeof(I);
    var valueProperty = i.GetProperty("Value");
    var value = valueProperty.GetValue(c);
    Debug.WriteLine(value);
}

public interface I
{
    string Value { get; }
}

public class C : I
{
    string I.Value { get { return "Test"; } }
}

Output:

Test

If you want to access it much more using names:

void Main()
{
    var c = new C();
    // TODO: Check if C implements I
    var i = c.GetType().GetInterface("I");
    if (i != null)
    {
        var valueProperty = i.GetProperty("Value");
        var value = valueProperty.GetValue(c);
        Debug.WriteLine(value);
    }
}

public interface I
{
    string Value { get; }
}

public class C : I
{
    string I.Value { get { return "Test"; } }
}


来源:https://stackoverflow.com/questions/21673363/how-do-i-retrieve-a-reference-to-a-subobject-using-reflection-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!