C# 获取实现类型的具体属性
给定以下类C# 获取实现类型的具体属性,c#,reflection,C#,Reflection,给定以下类 public Foo { public Foo() { this.Bar = new Bar(); } public IBar Bar{ get; set;} } public Bar : IBar { // implemented properties } 如何使用反射在Foo上获得属性栏的具体实现 instance.GetType().GetProperty("Bar").PropertyType 仅生成接口。如果试图获取实现IBar的类型,则应
public Foo
{
public Foo() {
this.Bar = new Bar();
}
public IBar Bar{ get; set;}
}
public Bar : IBar
{
// implemented properties
}
如何使用反射在Foo上获得属性栏的具体实现
instance.GetType().GetProperty("Bar").PropertyType
仅生成接口。如果试图获取实现IBar的类型,则应获取其值并获取类型:
var type = instance.GetType().GetProperty("Bar").GetValue(instance,null).GetType()
除非您还获得属性
Bar
的实际值,否则我很确定您不能。自.NET 4.5(2012年起)以来,有一个新的属性,因此您可以删除丑陋的,null
部分。(当然,没有反射,您可以执行instace.Bar.GetType()
,但这可能不是@JamesSouth所要求的。)