如果我知道某个泛型类型参数是一个数组,我该如何将其转换为数组或IEnumerable,以便我可以看到它的项目?对于例如
public class Foo<T> { public T Value { get; set; } public void Print() { if (Value.GetType().IsArray) foreach (var item in Value /*How do I cast this to Array or IEnumerable*/) Console.WriteLine(item); } }尝试这样的事情:
public void Print() { var array = Value as Array; if (array != null) foreach (var item in array) Console.WriteLine(item); }
as关键字:
The as operator is like a cast operation. However, if the conversion isn’t possible, as returns null instead of raising an exception.
精彩评论