检查var是否为任何对象的列表 [英] Check if var is a List of any kind of objects
问题描述
我正在使用.NET Framework 4.6.1和C#开发应用程序.
I'm developing an application with .NET Framework 4.6.1 and C#.
我想这样做:
var val = actionArguments[key];
if (val is List<T> as class)
我想检查 val
是否是任何对象的 List
,但是该语句无法编译.
I want to check if val
is a List
of any kind of object but that statement doesn't compile.
如何检查声明为var的变量是否为列表?
How can I check if a variable declared as var is a List?
在我的应用程序中,var是 List< Code>
. Code
是我制作的一个自定义类.而 List
是 System.Generic.Collections
.
On my application var is List<Code>
. Code
is a custom class that I made. And List
is System.Generic.Collections
.
推荐答案
由于 List< T>
还实现了非通用的 IList
接口,因此您只需检查一下
Since List<T>
is also implementing the non-generic IList
interface, you can simply check
if (val is IList)
这并不是说可以假设 IList
的任何东西必然是 List< T>
.但是,对于OP,就是让一些索引器返回 object
,并且需要在特定(也许是已知的)类型之间进行区别,避免使用 GetType()
并依赖 IList
是否足够用于此目的.
That's not to say that one can assume that anything that is IList
is neccessarily a List<T>
. But, in the case of the OP, that is having some indexer returning an object
and needs to differ between specific (perhaps known) types, avoiding GetType()
and relying on is IList
is good enough for this purpose.
请参见 MSDN
这篇关于检查var是否为任何对象的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!