更新时间:2023-02-12 18:34:40
这里的关键不是变种,但foreach循环。 foreach循环可以有选择地投迭代器除了迭代本身。
The point here is not var, but the foreach loop. The foreach loop can optionally cast the iterator in addition to iterating itself.
所以,你可以做到以下几点:
So you can do the following:
List<object> test = new List<object>();
test.Add(1);
test.Add(2);
test.Add(3);
foreach( int i in test ){
i.Dump();
}
因此,即使名单类型的对象,它可以被铸造为int的在foreach里飞。
So even if the list is of type object, it can be casted to int on the fly inside the foreach.