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

本文关键字:获取 集合 属性 const struct | 更新日期: 2023-09-27 17:54:22

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

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();

有人有什么想法吗?谢谢。

EDIT:这是最终为我工作的:

from d in typeof(MyStruct).GetFields()
select d.GetValue(new MyStruct());

感谢Jonathan Henson和JaredPar的帮助!

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

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

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

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

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

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

GetProperties将返回您的属性。属性有get和/或set方法。

到目前为止,你的结构还没有属性。如果您想要属性,请尝试:

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

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