c# - 遍历结构成员

标签 c#

假设我们有一个结构

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/

相关文章:

c# - ASP.net C#崩溃一行

c# - 添加具有相同接口(interface)的 HttpClient 最终具有相同的基本 url Asp.Net Core

c# - Mvc RenderAction 性能与 RenderPartial

c# - 控制 MouseLeave 事件的问题

c# - LINQ to Entities 中的 SQL 排名

c# - 从外部配置文件读取连接字符串

c# - Windows Mobile : Is there any library to build attractive interfaces?

c# - 为什么 Func<T> 不叫 Meth<T>?

c# - 从 C++ ASIO 库用 C# 录制音频流

c# - 如果 @html.actionlink 控件中未提供 Controller 名称,则采用哪个 Controller ?