c#6.0和反射,获取Property Initializers的值
本文关键字:Property Initializers 的值 获取 反射 c#6 | 更新日期: 2023-09-27 18:19:29
我一直在尝试反射,但我有一个问题。
比方说,我有一个类,在这个类中,我有用c#6.0 的新功能初始化的属性
Class MyClass()
{
public string SomeProperty{ get; set; } = "SomeValue";
}
有没有任何方法可以在不初始化类的情况下,通过反思获得这个值?
我知道我可以做到;
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; }
}
}
反射是关于元数据的。metadata中没有存储任何"SomeValue"。您所能做的就是以规则的方式读取属性值。
我知道我可以使用一个字段来获得值
在不实例化对象的情况下,您只能获得静态字段的值
要获得实例字段的值,显然需要对象的实例。
或者,如果您需要反射元数据中属性的默认值,您可以使用Attributes(其中一个来自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;