获得premade结构的所有值? C#

时间:2013-06-27 15:38:38

标签: c# struct

在C#中,我有一个非常庞大的结构,我想轻松地遍历它,而不是手动输入它们。

我尝试使用:

Type structType = typeof(myStruct);
System.Reflection.FieldInfo[] fields = structType.GetFields();
for(int i=0; i<fields.Length-1; i++)
{
    richTextBox1.Text += fields[i].Name + "\n";
}

其中myStruct是一个巨大的结构,但是你不能将变量结构传递给它,只有它们自己的结构。

基本上我想做的是:

public struct myStruct
{
    public string myName;
    public int myAge;
    ...
    ...
}

//in code
myStruct a = readStructFromFile( filename );
string text = "";
foreach(field in a)
{
    text += field.name + ": " + file.value;
}

那可能吗?

2 个答案:

答案 0 :(得分:2)

使用FieldInfo.GetValue。由于结构是meant to be small,所以更大的结构应该是类。

myStruct a = readStructFromFile( filename );

Type structType = typeof(myStruct);
System.Reflection.FieldInfo[] fields = structType.GetFields();

var builder = new StringBuilder();

foreach(var field in fields)
{
    builder.Append(string.Format("{0} {1}\n",
                                 field.Name,
                                 field.GetValue(a).ToString());

}

richTextBox1.Text += builder.ToString();

答案 1 :(得分:0)

我的建议是编写一些简单的代码生成例程来生成接近您想要的代码并将其复制到剪贴板。然后将其粘贴到您的程序中,并进行任何必要的调整。

必须编写大量的样板代码通常意味着您正在做的事情或您正在使用的语言/框架中的设计缺陷。根据您正在做的事情,故障可能是前者或后者。

有些情况下大型结构是合适的;如果某种类型的每个变量都应该封装一个固定的独立值集合,那么一个暴露字段结构就能完美地表达出来。在事情开始变得如此之大以至于产生堆栈溢出的风险之前,有利于使用4场结构而不是4场结构的因素对于20场结构而不是20场类更有意义。 / p>

使用结构编程与使用类编程之间存在一些明显的差异。如果使用不可变类,则从类实例生成除了少数字段之外相同的新实例是困难的。如果使用可变类,则可能难以确保每个变量都封装其自己的独立值集。假设一个人有List<classWithPropertyX> myListmyList[0]拥有X为3的实例。有人希望myList[0]持有X为4的实例,但是不影响与X类型的任何其他变量或存储位置关联的classWithPropertyX属性的值。

正确的方法可能是

myList[0].X = 4;

但这可能会产生不必要的副作用。也许需要使用

myList[0] = myList[0].WithX(4);

或者

var temp = myList[0];
myList[0] = new classWithPropertyX(temp.this, 4, temp.that, temp.theOther, etc.);

可能需要检查大量代码以确定哪种技术是合适的。相比之下,如果有一个List<structWithExposedFieldX> myList正确的代码是:

var temp = myList[0];
temp.X = 4;
myList[0] = temp;

唯一需要知道正确方法的信息是structWithExposedFieldX是一个具有公开字段X的结构。