具有方法接口的 C# 泛型约束

C# Generics constraint with Interface to a method

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

我有这个 class:


    Transport<T> where T: ISomething

我有另一个 class,我可以在其中使用实现我的 ISomething 的泛型来实现我的“传输”class。像这样:


    public class Route 
    {
        Transport<ISomething> Transport;
        public Route(Transport<ISomething> t)
        {
            Transport = t;
        }
    }

我希望能够调用我的构造函数


    Transport<Potatoes> myTransport = GetAllPotatoes();
    
    Route myRoute = new Route(myTransport);

有办法吗?我是仿制药的新手,并且(作为非英语母语人士)我无法使用正确的关键字自己找到答案。

谢谢。

为清楚起见编辑: 土豆实现了 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);

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

的非泛型基础 class

例如:

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