开发者

.NET reflection - Get Declaring class type from instance property

开发者 https://www.devze.com 2023-02-11 01:29 出处:网络
Is it possible to get the type of a class from a property instance I tried the following var model = new MyModel(\"SomeValueForMyPr开发者_开发百科operty\")

Is it possible to get the type of a class from a property instance

I tried the following

var model = new MyModel("SomeValueForMyPr开发者_开发百科operty")

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

But the result is always not for both DeclaringType and ReflectedType


There is no direct link from a Type to a class declaring a property of that type.

You'll need to use a 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;
0

精彩评论

暂无评论...
验证码 换一张
取 消