我有一个看起来像这样的结构:
public struct MyStruct
{
public const string Property1 = "blah blah blah";
public const string Property2 = "foo";
public const string Property3 = "bar";
}
我想以编程方式检索MyStruct的const属性值的集合。 到目前为止,我已经尝试过这个并没有成功:
var x = from d in typeof(MyStruct).GetProperties()
select d.GetConstantValue();
有人有什么想法吗?感谢。
编辑:这最终对我有用:
from d in typeof(MyStruct).GetFields()
select d.GetValue(new MyStruct());
感谢Jonathan Henson和JaredPar的所有帮助!
答案 0 :(得分:15)
这些字段不是属性,因此您需要使用GetFields
方法
var x = from d in typeof(MyStruct).GetFields()
select d.GetRawConstantValue();
此外,我相信您正在寻找方法GetRawConstantValue
而不是GetConstantValue
答案 1 :(得分:3)
这里有一个不同的版本来获取实际的字符串数组:
string[] myStrings = typeof(MyStruct).GetFields()
.Select(a => a.GetRawConstantValue()
.ToString()).ToArray();
答案 2 :(得分:2)
GetProperties将返回您的属性。属性已获取和/或设置方法。
到目前为止,您的结构还没有属性。如果你想要属性,请尝试:
private const string property1 = "blah blah";
public string Property1
{
get { return property1; }
}
此外,您可以使用GetMembers()返回所有成员,这将返回您当前代码中的“属性”。