假设我们有一个结构
Struct myStruct
{
int var1;
int var2;
string var3;
.
.
}
是否可以通过使用 foreach 来遍历结构的成员?我读过一些关于反射(reflection)的东西,但我不确定如何在这里应用它。
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
最佳答案
您应用反射的方式与正常方式几乎相同,使用 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));
}
请注意,如果结构公开了属性(几乎肯定应该如此),您可以使用 Type.GetProperties
来获取这些属性。
(如评论中所述,一开始这可能不是一件好事,而且一般我对用户定义的结构持怀疑态度,但我想我会无论如何包括实际答案......)
编辑:现在看来您对设置字段感兴趣,由于值类型的工作方式,这会稍微复杂一些(是的,这确实不应该 是一个结构。)您需要装箱一次,在单个装箱实例上设置值,然后在最后取消装箱:
object boxed = new MyStruct();
// Call FieldInfo.SetValue(boxed, newValue) etc
MyStruct unboxed = (MyStruct) boxed;
关于c# - 遍历结构成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7613782/