检查var是否为任何对象的列表

编程入门 行业动态 更新时间:2024-10-10 12:16:26
本文介绍了检查var是否为任何对象的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在使用.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是否为任何对象的列表

本文发布于:2023-11-09 11:46:14,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1572290.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:对象   列表   var

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!