通过结构成员迭代 [英] Iterating through Struct members

查看:195
本文介绍了通过结构成员迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有一个结构



 结构体MYSTRUCT 
{
INT VAR1;
INT VAR2;
串VAR3;


}

是否有可能通过可能使用的foreach通过结构成员重复?我已阅读反思一些东西,但我不知道如何应用在这里。




有在结构中约20变数。我想读值
关文件,并试图将它们分配给变量,但不希望
调用file.ReadLine()的20倍。我想通过一个循环



解决方案

您应用访问该成员
变量在几乎相同的方式与普通的反射,使用 Type.GetFields

  MYSTRUCT structValue =新MYSTRUCT(...); 

的foreach(typeof运算中的VAR场(MYSTRUCT).GetFields(BindingFlags.Instance |
BindingFlags.NonPublic可|
BindingFlags.Public))
{
Console.WriteLine({0} = {1},field.Name,field.GetValue(structValue));
}

请注意,如果结构暴露性质(因为它几乎肯定应该)你可以使用 Type.GetProperties 来得到那些。



(正如在评论中指出,这很可能不是一个好事情在首位做的,一般的我很可疑用户定义的结构,但我想我会包括实际的答案反正...)



编辑:现在看来,你有兴趣的设置的领域,也由于这样的值类型作品的稍微复杂(是的,这确实的不应该'T 的是一个结构)你会想框的一次的,对单一包装实例,并在年底再拆箱设定值:

 对象盒装=新MYSTRUCT(); 

//调用FieldInfo.SetValue(盒装,newValue)以等

MYSTRUCT拆箱=(MYSTRUCT)盒装;


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

解决方案

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;

这篇关于通过结构成员迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆