[英]Why can't I declare generic List<T> as return type for interface method?
Why can't I create an interface method with return type List<T>
? 为什么我不能创建返回类型为List<T>
的接口方法? I'm encountering this compile error "The type or namespace name 'T' could not be found" 我遇到此编译错误“找不到类型或名称空间名称'T'”
interface ILoader
{
List<T> LoadValues();
}
Appreciate any of your input. 感谢您的任何投入。
What is T
supposed to be in your interface? T
应该在您的界面中是什么? For the compiler, T
is just an unknown identifier at that point. 对于编译器, T
在那时只是一个未知的标识符。
You need to specify something for T
, some type that is used as the type argument for List<T>
. 您需要为T
指定一些内容,将某些类型用作List<T>
的类型参数。
Depending on what you want to achieve, there are four options: 根据您要实现的目标,有四个选项:
Declare T
as a generic parameter on the interface/class level: 在接口/类级别上将T
声明为通用参数:
interface ILoader<T> { List<T> LoadValues(); }
Declare T
as a generic parameter on the method level: 将T
声明为方法级别的通用参数:
interface ILoader { List<T> LoadValues<T>(); }
Assign a fixed type as T
; 将固定类型分配为T
; eg int
(wlog): 例如int
(wlog):
interface ILoader { List<int> LoadValues(); }
Declare T
as a generic parameter on a higher nesting level (thanks to Jeppe Stig Nielsen for pointing out this possibility): 在较高的嵌套级别上将T
声明为通用参数(感谢Jeppe Stig Nielsen指出了这种可能性):
class Outer<T> { interface ILoader { List<T> LoadValues(); } }
The T generic parameter must also be declared in the interface. T泛型参数也必须在接口中声明。 Something like this: 像这样:
interface ILoader<T>
{
List<T> LoadValues();
}
You should do something like this: 您应该执行以下操作:
interface ILoader<T>
{
List<T> LoadValues();
}
Or 要么
interface ILoader
{
List<T> LoadValues<T>();
}
Or even, possibly: 甚至可能:
interface ILoader
{
List<dynamic> LoadValues();
}
^Isn't the best idea but usable. ^不是最好的主意,但可以使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.