且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C#泛型,方法'xxxxxxxx'的类型参数不能用于使用。

更新时间:2022-04-16 01:09:05

泛型类型参数的类型参数只有在输入参数中使用时才能推断。在所有其他情况下,必须明确声明类型参数。



可以推断所有这些的类型参数:

The type argument for a generic type parameter can only be inferred if it is used in an input parameter. In all other cases, the type parameter must be declared explicitly.

The type parameter can be inferred for all of these:
public static T Foo<T>(T bar) { ... }
int x = Foo(42);

public static T FirstOrDefault<T>(IEnumerable<T> source) { ... }
string item = FirstOrDefault(myListOfStrings);

public static IEnumerable<T> Where<T>(IEnumerable<T> source, Func<T, bool> predicate) { ... }
IEnumerable<Bar> filteredList = Where(myListOfBars, bar => someCondition);





但是当没有任何输入参数与type参数相关时,你必须明确指定type参数:



But when none of the input parameters are related to the type parameter, you have to specify the type parameter explicitly:

public static List<T> MakeAList<T>(int x, string y) { ... }

List<Bar> myList = MakeAList(42, "Hello"); // Compiler error
List<Bar> myList = MakeAList<Bar>(42, "Hello"); // OK





因此,在您的示例中,您需要:



So, in your example, you need:

lstTransferObject = GetDtoList<TransferObject>(a, b);





HOWEVER ,这个无效。您的代码将编译,但您将在运行时获得异常,因为您尝试将一种类型的对象添加到不同类型的列表中。如果用对象 T 替换动态键工作,你会得到一个编译错误,它会告诉你问题是什么。



如果你想返回一个动态列表对象,那么你的方法应该返回 List< dynamic> 。如果要返回特定类型的列表,则需要在循环中创建该特定类型的实例。



HOWEVER, this will not work. Your code will compile, but you will get an exception at runtime, because you're trying to add an object of one type to a list of a different type. If you replace the dynamic keywork with either object or T, you'll get a compiler error which shows you what the problem is.

If you want to return a list of dynamic objects, then your method should return List<dynamic>. If you want to return a list of a specific type, then you need to create an instance of that specific type in your loop.