.NET反射-从实例属性获取声明类的类型 [英] .NET reflection - Get Declaring class type from instance property

查看:269
本文介绍了.NET反射-从实例属性获取声明类的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以从属性实例中获取类的类型

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

我尝试了以下

var model = new MyModel("SomeValueForMyProperty")

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

但是结果始终不会同时适用于DeclaringType和ReflectedType

But the result is always not for both DeclaringType and ReflectedType

推荐答案

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

There is no direct link from a Type to a class declaring a property of that 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;

这篇关于.NET反射-从实例属性获取声明类的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆