[英]How do I retrieve a reference to a subobject using Reflection in C#?
I'm trying to use duck typing using reflection in C#. 我正在尝试在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. 有效地我需要
as
使用反射。
The first part is easy 第一部分很容易
var interfaceOfInterest =
randomObject.GetType().GetInterface("Full.Interface.Name.Here");
which will either retrieve the interface description or null. 它将检索接口描述或为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. 您不需要通过接口类型简单地访问接口的属性,但是每当需要传递实例时,只需传递原始对象实例即可。
Here is a LINQPad program that demonstrates: 这是一个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"; } }
}
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"; } }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.