我正在尝试构建一种方法来检查列表是否为空:
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 扩展方法。
Cast
是 IEnumerable
的扩展方法,而大多数其他 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/