C# Object Traversal Guide
In C#, you can use a foreach loop to iterate over data of type object. First, convert the object data to the appropriate type, and then perform the iteration. Here is an example code:
object[] myArray = { 1, "two", 3.0, 4 }; // 假设有一个包含不同类型的object数组
foreach (object obj in myArray)
{
if (obj is int) // 检查对象类型
{
int num = (int)obj; // 将对象转换为int类型
Console.WriteLine("整数: " + num);
}
else if (obj is string)
{
string str = (string)obj; // 将对象转换为string类型
Console.WriteLine("字符串: " + str);
}
else if (obj is double)
{
double dbl = (double)obj; // 将对象转换为double类型
Console.WriteLine("双精度浮点数: " + dbl);
}
}
Running the above code will produce the following results:
整数: 1
字符串: two
双精度浮点数: 3
整数: 4
It is important to make sure the conversion of object data is safe when traversing through it, as there may be runtime exceptions. It is recommended to use the ‘is’ keyword for type checking before conversion to ensure safety.