使用循环变量作为字段变量名称的一部分

时间:2015-01-26 00:38:30

标签: c#

我在这里定义了8种不同的C#整数类型:

// Eight C# predefined integer types:
sbyte i1 = -128;
short i2 = -32768;
int i3 = -2147483648;
long i4 = -9223372036854775808;
byte i5 = 255;
ushort i6 = 65535;
uint i7 = 4294967295;
ulong i8 = 18446744073709551615;

我能够像这样手动打印它们:

Console.WriteLine("i1 has a type of: {0}", i1.GetType());
Console.WriteLine("i2 has a type of: {0}", i2.GetType());
Console.WriteLine("i3 has a type of: {0}", i3.GetType());
Console.WriteLine("i4 has a type of: {0}", i4.GetType());
Console.WriteLine("i5 has a type of: {0}", i5.GetType());
Console.WriteLine("i6 has a type of: {0}", i6.GetType());
Console.WriteLine("i7 has a type of: {0}", i7.GetType());
Console.WriteLine("i8 has a type of: {0}", i8.GetType());

但是,我宁愿循环遍历它们并打印它们的类型:

// print types
for (int j = 1; j < 9; j++){
Console.WriteLine("i{0} has a type of: {1}", j, XXX.GetType());
}

将i和j组合为变量名称的最佳方法是什么,以便我可以获得它的类型?

2 个答案:

答案 0 :(得分:1)

List<object> l = new List<object>();
l.Add(i1);
l.Add(i2);
// and so on...

int j=0;
foreach(var xxx in l)
{
   Console.WriteLine("i{0} has a type of: {1}", j,xxx.GetType());
   j++;
}

答案 1 :(得分:1)

如果要循环,则需要一个枚举器,例如在对象实现IEnumerable时提供的枚举器。所以你可以做的是将所有这些类型添加到List中。此代码示例使用字典并存储特定类型的最小值。

// declare and define
IDictionary<Type, object> integers = new Dictionary<Type, object>();
integers.Add(typeof(sbyte), sbyte.MinValue);
integers.Add(typeof(short), short.MinValue);
// etc.

// display
int counter = 0;
foreach (KeyValuePair<Type, object> integer in integers)
{
    Console.WriteLine(
        "i{0} has a type of {1} with a minimum value of {2}.",
        ++counter,
        integer.Key,
        integer.Value);
}