【发布时间】:2021-07-01 06:40:22
【问题描述】:
可能标题不正确,但我想不出更准确的东西。
我有这门课:
Transport<T> where T: ISomething
我有另一个类,我可以在其中使用我的“Transport”类和实现我的 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。
【问题讨论】:
-
你能显示你在
Transport类中有哪些成员吗? -
Transport<Potatoes>不是Transport<ISomething>。泛型参数化不会导致构造类型获得与原始类型相同的继承/实现关系。 -
你的 Potatoes 课程由什么组成?它也是从 ISomething 接口实现的?
-
我实际上认为您在这里根本不需要泛型。你
TransportISomething无论如何都在你的Route上。 -
当然,我的 Potatoes 类实现了 ISomething
标签: c# generics interface constraints