C#泛型约束与方法接口

时间:2021-07-01 06:40:22

标签: c# generics interface constraints

可能标题不对,但我想不出更准确的东西。

我有这门课:


    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。

2 个答案:

答案 0 :(得分:1)

您也可以使路由通用,如下所示:

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);

然而,我想这不是您想要的,因为您希望能够创建非通用的路由。在这种情况下,您需要具有 RouteTransport 的非泛型基类。

例如:

public interface ITransport {}

public class Transport<T> : ITransport 
where T: ISomething
{
}

public class Route
    {
        ITransport Transport;
        public Route(ITransport t)
        {
            Transport = t;
        }
    }

答案 1 :(得分:1)

您可以使用协变接口...在您的情况下:

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