是否可以使用 IEnumerable 为 class 中的字段创建一个 foreach 循环?

Is it possible to make a foreach loop for fields in a class using IEnumerable?

我想知道是否可以使 class 的字段可枚举,以便您可以使用 for 或 foreach 循环遍历它们。我看过一些描述如何使包含其他结构的结构以这种方式被枚举的版本。

我也知道我可能完全误读了关于这个主题的MSDN article

所以我的问题是,是否可以使用 IEnumerable 或类似接口迭代 class 中的字段?

我想做这样的事情:

private class Integers
{
    public int int1;
    public int int2;
    public int int3;
    public int int4;
    public int int5;
    public int int6;
    public int int7;
    public int int8;
}

foreach(int I in Integers){
    Console.WriteLine(I); 
}

听起来您正在寻找一个枚举:enum docs

可以使用 Reflection.
迭代 class 中的字段 这是一个例子:

public class MyClass
{
    public int I1;
    public int I2;
    public int I3;
    public int I4;
}
// typeof(MyClass).GetFields() return FieldInfo[], which is IEnumerable<T>
foreach (var field in typeof(MyClass).GetFields())
{
    Console.WriteLine(field.Name);
}

// I1
// I2
// I3
// I4

但是,您可能应该使用其他东西。数组可能更合适。

可以用反射来做:

var Integers = new Integers{
    int1 = 50,
    int2 = 42,
    // etc. ...
};
foreach (var field in typeof(Integers).GetFields())
{
    Console.WriteLine(field.GetValue(Integers));
}

但是您想要这样做的事实可能表明您根本不应该使用 class。

你想要枚举吗?

private enum Integers
{
    int1 = 50,
    int2 = 42,
    // etc.
}

foreach (var value in Enum.GetValues(typeof(Integers)).Cast<int>())
{
    Console.WriteLine(value);
}

列表会更合适吗?

var integers = new List<int>() { 50, 42, /*etc*/};
foreach (var value in integers)
{
    Console.WriteLine(value);
}

还是字典?

var integers = new Dictionary<string, int>() { 
["int1"] = 50, 
["int2"] = 42, 
/*etc*/
};
foreach (var keyValuePair in integers)
{
    Console.WriteLine(keyValuePair.Value);
}