c# - 没有从 'System.Collections.Generic.IList<double>' 到 'System.Collections.IList' 的隐式引用转换

标签 c# .net generics

我正在尝试构建一种方法来检查列表是否为空:

    public static T1 NotEmpty<T1>(T1 argument, string message = null) where T1 : class, IEnumerable
    {
        if (argument == null)
        {
            throw new ArgumentNullException(message);
        }
        if(!argument.Any())
        {
            throw new ArgumentException(message);
        }
        return argument;
    }

然后像这样使用它:

public void MyMethod(IList<double> stuff)
{
    _stuff = NotEmpty(stuff);
    ....
}

但它无法编译。扩展方法Any()似乎只在 IEnumerable 的通用版本上定义.但是,我无法定义 NotEmpty方法使得通用参数实现 IEnumerable 的通用版本并且编译器能够自动计算出类型。我最不想做的就是手动输入所有类型。

是否有可能以比下面给出的方式更优雅的方式实现它?

    public static T1 NotEmpty<T1>(T1 argument, string message = null) where T1 : class, IEnumerable
    {
        if (argument == null)
        {
            throw new ArgumentNullException(message);
        }
        if(!argument.GetEnumerator().MoveNext())
        {
            throw new ArgumentException(message);
        }
        return argument;
    }

最佳答案

你可以 Cast 以便您可以使用 LINQ 扩展方法。

CastIEnumerable 的扩展方法,而大多数其他 LINQ 扩展方法(例如 Any )仅适用于 IEnumerable<T> .自从使用 IEnumerable<T>会使您的代码复杂化(由于涉及两个泛型类型),我可能会这样做:

public static T1 NotEmpty<T1>(T1 argument, string message = null) where T1 : class, IEnumerable
{
    if (argument == null)
    {
        throw new ArgumentNullException(message);
    }
    if(!argument.Cast<object>().Any())
    {
        throw new ArgumentException(message);
    }
    return argument;
}

关于c# - 没有从 'System.Collections.Generic.IList<double>' 到 'System.Collections.IList' 的隐式引用转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21141178/

相关文章:

c# - 如何防止点击通过控件传递到其下方的控件

c# - 两个 DateTimes 之间的时差?

spring - 嵌套具体化参数无法创建 ParameterizedTypeReference

java - 使用 Generic VarArgs 在 Java 中进行不明确的方法调用

generics - 我可以在没有未经检查的异常的情况下使用 Collections.EMPTYLIST 吗?

c# - 当最后一个方法调用是有条件的时,为什么 C# 编译器会删除一连串的方法调用?

c# - 如何将整数格式化为 ASCII/Unicode 字符(不只是转换为 char)

c# - 如何从创建它的代码中获取对 WCF 服务对象的引用?

c# - notepad++ 插件 - 阅读所有文档的文本

c# - 如果在 sql server 中回滚事务,它会删除临时表(在事务中创建)吗?