I've got a struct that looks like this:
public struct MyStruct
{
public const string Property1 = "blah blah blah";
public const string Property2 = "foo";
public const string Property3 = "bar";
}
I want to programmatically retrieve a collection of MyStruct's const properties' values. So far I've tried this with no success:
var x = from d in typeof(MyStruct).GetProperties()
select d.GetConstantValue();
Anyone have any ideas? Thanks.
EDIT: Here is what eventually worked for me:
from d in t开发者_开发知识库ypeof(MyStruct).GetFields()
select d.GetValue(new MyStruct());
Thank you Jonathan Henson and JaredPar for all your help!
These are fields not properties and hence you need to use the GetFields
method
var x = from d in typeof(MyStruct).GetFields()
select d.GetRawConstantValue();
Also I believe you're looking for the method GetRawConstantValue
instead of GetConstantValue
Here's a bit different version to get the actual array of strings:
string[] myStrings = typeof(MyStruct).GetFields()
.Select(a => a.GetRawConstantValue()
.ToString()).ToArray();
GetProperties will return your Properties. Properties have get and/or set methods.
As of yet your structure has no properties. If you want properties try:
private const string property1 = "blah blah";
public string Property1
{
get { return property1; }
}
furthermore, you could use GetMembers() to return all of your members, this would return your "properties" in your current code.
精彩评论