【问题标题】:Casting to a generic of any type in C#在 C# 中转换为任何类型的泛型
【发布时间】:2014-10-22 11:22:52
【问题描述】:

我有一个object value,它可能代表不同类型的对象(字符串、枚举、列表等)。我要做的是检查变量是否为空列表,如下所示:

(value is List<object> && ((List<object>)value).Count == 0)

(value is List<dynamic> && ((List<dynamic>)value).Count == 0)

但是对于真正的空列表,两者都返回 false。
我想知道最好的方法是什么,以及 C# 中是否有类似 Java 的 List&lt;?&gt; 之类的东西。

【问题讨论】:

标签: c# generics casting


【解决方案1】:

您可以将其投射到IList

if( (value as IList).Count == 0 )

如果不确定该值是否实现IList,最好检查null:

var list = value as IList;
if(list != null && list.Count == 0)

【讨论】:

  • @GeneMarin using System.Collections;
【解决方案2】:

你可以创建一个辅助类:

public static class CollectionHelpers
{
    public static bool IsNullOrEmpty(this ICollection collection)
    {
        return collection == null || collection.Count == 0;
    }
}

并像这样使用它:

class Program
{
    static void Main(string[] args)
    {
        object list = new List<int> { 1, 2, 3 };
        Console.WriteLine((list as ICollection).IsNullOrEmpty());
    }
}

class Program
{
    static void Main(string[] args)
    {
        var list = new List<int>();
        Console.WriteLine(list.IsNullOrEmpty());
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-17
    • 2022-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多