c# 6.0 和反射,获取 属性 初始化器的值

c# 6.0 and reflection, getting value of Property Initializers

我一直在尝试反射,但我有一个问题。

假设我有一个 class,在这个 class 中,我有一个 属性 使用 c# 6.0

的新功能初始化
Class MyClass()
{
   public string SomeProperty{ get; set; } = "SomeValue";
}

有没有办法通过反射获得这个值,而不用初始化 class?

我知道我能做到;

var foo= new MyClass();
var value = foo.GetType().GetProperty("SomeProperty").GetValue(foo);

但我想做的是与此类似的事情;

typeof(MyClass).GetProperty("SomeProperty").GetValue();

我知道我可以使用字段来获取值。但它必须是 属性。

谢谢。

这只是一个语法糖。 这个:

class MyClass()
{
   public string SomeProperty{ get; set; } = "SomeValue";
}

将被编译器解包为:

class MyClass()
{
   public MyClass()
   {
       _someProperty = "SomeValue";
   }

   // actually, backing field name will be different,
   // but it doesn't matter for this question
   private string _someProperty;

   public string SomeProperty
   { 
        get { return _someProperty; }
        set { _someProperty = value; }
   }
}

反射是关于元数据的。 metatada 中没有存储任何 "SomeValue"。您所能做的就是以常规方式读取 属性 值。

I know I could use a field to get the value

不实例化对象,只能获取静态字段的值。
要获取实例字段的值,显然,您需要一个对象实例。

或者,如果您需要反射元数据中的默认值 属性,您可以使用属性,其中之一来自 System.ComponentModel,执行以下工作:DefaultValue。例如:

using System.ComponentModel;

class MyClass()
{
   [DefaultValue("SomeValue")]
   public string SomeProperty{ get; set; } = "SomeValue";
}
//
var propertyInfo = typeof(MyClass).GetProperty("SomeProperty");
var defaultValue = (DefaultValue)Attribute.GetCustomeAttribute(propertyInfo, typeof(DefaultValue));
var value = defaultValue.Value;