Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
302 views
in Technique[技术] by (71.8m points)

c# - Iterating through Struct members

Lets say we have a struct

Struct myStruct
{
   int var1;
   int var2;
   string var3;
   .
   .
}

Is it possible to to iterate through the structure's members by maybe using foreach? I have read some things on reflection, but I am not sure how to apply that here.

There are about 20 variables in the struct. I am trying to read values off a file and trying to assign them to the variables but don't want to call file.ReadLine() 20 times. I am trying to access the member variables through a loop

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You apply reflection in pretty much the same way as normal, using Type.GetFields:

MyStruct structValue = new MyStruct(...);

foreach (var field in typeof(MyStruct).GetFields(BindingFlags.Instance |
                                                 BindingFlags.NonPublic |
                                                 BindingFlags.Public))
{
     Console.WriteLine("{0} = {1}", field.Name, field.GetValue(structValue));
}

Note that if the struct exposes properties (as it almost certainly should) you could use Type.GetProperties to get at those.

(As noted in comments, this may well not be a good thing to do in the first place, and in general I'm suspicious of user-defined structs, but I thought I'd include the actual answer anyway...)

EDIT: Now it seems you're interested in setting the fields, that's slightly more complicated due to the way value types work (and yes, this really shouldn't be a struct.) You'll want to box once, set values on the single boxed instance, and then unbox at the end:

object boxed = new MyStruct();

// Call FieldInfo.SetValue(boxed, newValue) etc

MyStruct unboxed = (MyStruct) boxed;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...