【问题标题】:.NET reflection - Get Declaring class type from instance property.NET 反射 - 从实例属性中获取声明类类型
【发布时间】:2011-06-28 09:55:02
【问题描述】:

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

我尝试了以下

var model = new MyModel("SomeValueForMyProperty")

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

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

【问题讨论】:

  • 你的意思是从属性的类型上声明属性的类型? public class Derp{ public string Herp{get;set;}} from typeof(string) 你想得到typeof(Derp)?
  • 既然你这样说 :) 我可以看到以这种方式使用 GetType() 并没有真正的意义。我想我需要访问 PropertyInfo,但不确定是否可以从属性实例本身获得

标签: .net reflection gettype


【解决方案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;

【讨论】:

    猜你喜欢
    • 2019-02-07
    • 1970-01-01
    • 1970-01-01
    • 2018-06-05
    • 1970-01-01
    • 2014-06-22
    • 1970-01-01
    • 1970-01-01
    • 2021-09-18
    相关资源
    最近更新 更多