能否从属性实例获取类的类型?
我尝试了以下方法:
var model = new MyModel("SomeValueForMyProperty")
Type declaringType = model.MyProperty.GetType().DeclaringType
但是结果通常对于声明类型和反射类型都无效。
能否从属性实例获取类的类型?
我尝试了以下方法:
var model = new MyModel("SomeValueForMyProperty")
Type declaringType = model.MyProperty.GetType().DeclaringType
一个 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;
typeof(string)
获取typeof(Derp)
,因为Derp
类中有一个名为Herp
的字符串属性。 - user1228