如何检查一个变量是否是某种IEnumerable [英] How to check if a variable is an IEnumerable of some sort
问题描述
variable.ToString()
。但是,我希望它评估列表和foreach通过他们,而不是打印 ListItem.ToString()
我的T4模板不知道什么类型变量会提前,这就是为什么这是通用的。
但是我现在生成的代码如下所示:
if(variable!= null)
if(变量是IEnumerable)//错误在这里
foreach )
Write(item.ToString());
在使用泛型类型System.Generic.Collections的标记行上出现编译器错误。 IEnumerable需要一个类型参数
我并不在意它是什么类型,我只是想知道是否可以通过变量进行foreach。我应该使用什么样的代码?解析方案
你已经接受了一个答案,因为泛型 IEnumerable< T>
实现非通用的 IEnumerable
,您可以转换为
//是否写入句柄为空?可能还需要一些理智。
var enumerable = variable作为System.Collections.IEnumerable;
if(enumerable!= null)
foreach(可枚举中的var项)
Write(item);
else
写(item);
basically I'm building a very generic T4 template and one of the things I need it to do is say print variable.ToString()
. However, I want it to evaluate lists and foreach through them and instead print ListItem.ToString()
My T4 template does not know what type variable
will be ahead of time, that is why this is so generic.
But my current code that gets generated looks like this:
if(variable!=null)
if(variable is IEnumerable) //error here
foreach(var item in variable)
Write(item.ToString());
I get a compiler error on the marked line for "Using the generic type System.Generic.Collections.IEnumerable requires one type argument"
I don't actually care what type it is though, I just want to know if you can foreach through the variable. What code should I use instead?
You have already accepted an answer however,since generic IEnumerable<T>
implements the non generic IEnumerable
you can just cast to that.
// Does write handle null? Might need some sanity aswell.
var enumerable = variable as System.Collections.IEnumerable;
if (enumerable != null)
foreach(var item in enumerable)
Write(item);
else
Write(item);
这篇关于如何检查一个变量是否是某种IEnumerable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!