该类型不能用作类型' T'在泛型类型或方法中。没有隐式的引用转换

时间:2016-05-05 13:07:22

标签: c# .net list generics

我试图编写一个通用方法来检查List是null还是空并抛出异常。

这就是我所拥有的:

public static void IsNullOrEmpty<T>(T argument) where T : List<T>
{
   if (argument == null || argument.Count == 0)
   {
        throw new ArgumentException("Argument " + nameof(argument) + " can't be null or empty list.");
   }
}

问题在于调用此方法;我试着像这样调用这个方法:

ThrowIf.Argument.IsNullOrEmpty<List<ParameterServiceReference.Parameter>>(options.Parameters);

其中options.Parameters的类型为:List<ParameterServiceReference.Parameter>.

我收到此错误:

There is no implicit reference conversion from 'System.Collections.Generic.List<ParameterServiceReference.Parameter>' to 'System.Collections.Generic.List<System.Collections.Generic.List<ParameterServiceReference.Parameter>>

如果我这样称呼方法:

ThrowIf.Argument.IsNullOrEmpty<ParameterServiceReference.Parameter>(options.Parameters);

我收到此错误:

cannot convert from 'System.Collections.Generic.List<Project.Layer.ParameterServiceReference.Parameter>' to 'Project.Layer.ParameterServiceReference.Parameter'

这种通用方法是否可以使用泛型集合,在解决方案中我将有许多不同类的通用列表,我认为编写这么多重载方法并不聪明。

3 个答案:

答案 0 :(得分:2)

您的泛型约束明确指出参数需要是某种类型,其中列表的泛型类型是本身。当您说where T : List<T>时,您说通用参数T必须是List<T>,其中T是您要添加的类型List<T>约束。

你应该真正做什么只是让方法接受T,而不是T,其中Listpublic static void IsNullOrEmpty<T>(List<T> argument) { //...

.header-table .column-2{
  position:relative;
}
.header-table .column-2 label {
  position: absolute;
  top:50%;
  margin-top:-11px;
  height:100%;
}

.header-table .column-2 input {
  height: 32px;
  line-height:32px;
}

答案 1 :(得分:0)

您不能拥有T : List<T>的约束,就像您不能拥有继承自MyList的类型MyList(或类型T继承自List<T>)。

只需使用public static void IsNullOrEmpty<T>(List<T> argument)

即可

答案 2 :(得分:0)

你可以这样:

public static void IsNullOrEmpty<S,T>(T argument) where T : List<S>
{
    if (argument == null || argument.Count == 0)
    {
        throw new ArgumentException("Argument " + nameof(argument) + " can't be null or empty list.");
    }
}

现在你可以打电话给你的方法:

ThrowIf.Argument.IsNullOrEmpty<ParameterServiceReference.Parameter, List<ParameterServiceReference.Parameter>>(options.Parameters);