C# 从struct';s常数性质
我有一个结构,看起来像这样:C# 从struct';s常数性质,c#,reflection,C#,Reflection,我有一个结构,看起来像这样: 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
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());
谢谢乔纳森·汉森和杰雷德·帕尔的帮助 GetProperties将返回您的属性。属性具有get和/或set方法 到目前为止,您的结构还没有属性。如果需要属性,请尝试:
private const string property1 = "blah blah";
public string Property1
{
get { return property1; }
}
此外,您可以使用GetMembers()返回所有成员,这将返回当前代码中的“属性”。这些字段不是属性,因此您需要使用
GetFields
方法
var x = from d in typeof(MyStruct).GetFields()
select d.GetRawConstantValue();
另外,我相信您正在寻找方法
getrawcantvalue
而不是GetConstantValue
这里有一个不同的版本来获取字符串的实际数组:
string[] myStrings = typeof(MyStruct).GetFields()
.Select(a => a.GetRawConstantValue()
.ToString()).ToArray();
您还可以使用属性设置值,例如:private string property1;公共字符串Property1{get{returnproperty1;}set{Property1=value;}}同样,在C#v3.5和更高版本中,您可以只执行get;并设置;我知道这是一个老问题/答案,但谢谢你。您是第一个指出它们是字段而不是属性的人。