从struct的const属性中获取值的集合

我有一个看起来像这样的结构:

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的所有帮助!

这些字段不是属性,因此您需要使用GetFields方法

  var x = from d in typeof(MyStruct).GetFields() select d.GetRawConstantValue(); 

另外我相信你正在寻找方法GetRawConstantValue而不是GetConstantValue

GetProperties将返回您的属性。 属性具有获取和/或设置方法。

截至目前,您的结构没有属性。 如果你想要属性尝试:

 private const string property1 = "blah blah"; public string Property1 { get { return property1; } } 

此外,您可以使用GetMembers()返回所有成员,这将返回您当前代码中的“属性”。

这里有一个不同的版本来获取实际的字符串数组:

 string[] myStrings = typeof(MyStruct).GetFields() .Select(a => a.GetRawConstantValue() .ToString()).ToArray();