Iterating through Struct members

后端 未结 1 1370
一向
一向 2020-12-05 05:15

Lets say we have a struct

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

Is it possible to to iterate through the

相关标签:
1条回答
  • 2020-12-05 06:15

    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;
    
    0 讨论(0)
提交回复
热议问题