2011-02-16 141 views
2

是否有可能从属性的实例获得一个类的类型.NET反射 - 获取从实例属性声明类类型

我尝试以下

var model = new MyModel("SomeValueForMyProperty") 

Type declaringType = model.MyProperty.GetType().DeclaringType 

但结果总是不DeclaringType和ReflectedType均为

+1

你的意思是该财产被宣布,从属性的类型的类型? `typeof(string)``public class Derp {public string Herp {get; set;}}```你想获得'typeof(Derp)`? – Will 2011-02-16 14:44:19

回答

1

Type到声明该类型属性的类没有直接链接。

你需要使用PropertyInfo

PropertyInfo propInfo = model.GetType().GetProperty("MyProperty"); 

// get the property value: 
object value = propInfo.GetValue(model, null); 
// get the property's declaring type: 
Type declaringType = propInfo.DeclaringType;