[英]C# Generics constraint with Interface to a method
可能标题不对,但我想不出更精确的东西。
我有这门课:
Transport<T> where T: ISomething
我有另一个类,我可以在其中使用我的“传输”类和实现我的 ISomething 的泛型。 像这样:
public class Route
{
Transport<ISomething> Transport;
public Route(Transport<ISomething> t)
{
Transport = t;
}
}
我希望能够调用我的构造函数
Transport<Potatoes> myTransport = GetAllPotatoes();
Route myRoute = new Route(myTransport);
有没有办法做到这一点? 我是泛型的新手,并且(作为非英语母语人士)我无法使用正确的关键字自己找到答案。
谢谢。
为清楚起见编辑:Potatoes 实现了 ISomething。
您也可以使路由通用,如下所示:
public class Route<T>
{
Transport<T> Transport;
public Route(Transport<T> t)
{
Transport = t;
}
}
然后你可以创建一个路由
Transport<Potatoes> myTransport = GetAllPotatoes();
Route<Potatoes> myRoute = new Route<Potatoes>(myTransport);
但是,我想这不是您想要的,因为您希望能够创建非通用的路由。 在这种情况下,您需要有一个Route
或Transport
的非通用基类。
例如:
public interface ITransport {}
public class Transport<T> : ITransport
where T: ISomething
{
}
public class Route
{
ITransport Transport;
public Route(ITransport t)
{
Transport = t;
}
}
您可以使用协变接口来实现...在您的情况下:
public interface ISomething {
}
public interface ITransport<out T> where T : ISomething
{
}
public class Transport<T> : ITransport<T> where T: ISomething
{
}
public class Potatoes : ISomething {
}
public class Route
{
ITransport<ISomething> Transport;
public Route(ITransport<ISomething> t)
{
Transport = t;
}
}
public class Program
{
public static void Main()
{
Transport<Potatoes> myTransport = null /* or getAllPotatoes */;
Route myRoute = new Route(myTransport);
}
}
请注意, Route
现在采用ITransport<T>
,而不是Transport<T>
。
类中的协方差不起作用,您需要一个接口。
这不会做任何事情,但只是让你看到它编译: https : //dotnetfiddle.net/T2Yd8N
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.