如何使用C#中的Reflection检索对子对象的引用? [英] How do I retrieve a reference to a subobject using Reflection in C#?

查看:115
本文介绍了如何使用C#中的Reflection检索对子对象的引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用C#中的反射进行鸭子打字。我有一个随机类型的对象,我想找到它是否实现了具有特定名称的接口,如果它实现 - 检索对该接口子对象的引用,以便稍后我可以通过该接口读取(获取)属性值。

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.

实际上我需要作为使用Reflection。

Effectively I need as using Reflection.

第一部分很简单

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

将检索接口描述或null。我们假设它不是空的。

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?

推荐答案

您不需要,只需通过接口类型访问接口的属性,但无论何时需要传递实例,只需传递原始对象实例。

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.

这是一个 LINQPad 程序演示:

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"; } }
}

输出:

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"; } }
}

这篇关于如何使用C#中的Reflection检索对子对象的引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆