C#泛型:在方法泛型的where子句中使用类泛型

and*_*esp 5 c# generics .net-2.0

任何人都可以解释为什么这不可能(至少在.Net 2.0中):

public class A<T>
{
    public void Method<U>() where U : T
    {
        ...
    }
}

...

A<K> obj = new A<K>();
obj.Method<J>();
Run Code Online (Sandbox Code Playgroud)

K是J的超类

编辑

我试图简化问题,以使问题更清晰,但我显然已经过头了.抱歉!

我想我的问题更具体一点.这是我的代码(基于):

public class Container<T>
{
    private static class PerType<U> where U : T
    {
        public static U item;
    }

    public U Get<U>() where U : T
    {
        return PerType<U>.item;
    }

    public void Set<U>(U newItem) where U : T
    {
        PerType<U>.item = newItem;
    }
}
Run Code Online (Sandbox Code Playgroud)

我收到这个错误:

Container.cs(13,24):错误CS0305:使用泛型类型 Container<T>.PerType<U>' requires2'类型参数

Yav*_*nyP 7

实际上这是可能的.这段代码编译并运行得很好:

public class A<T>
{
    public void Act<U>() where U : T
    {
        Console.Write("a");
    }
}

static void Main(string[] args)
{
  A<IEnumerable> a = new A<IEnumerable>();
  a.Act<List<int>>();
}
Run Code Online (Sandbox Code Playgroud)

什么是不可能的使用仿制药协方差/逆变,为解释在这里:

IEnumerable<Derived> d = new List<Derived>();
IEnumerable<Base> b = d;
Run Code Online (Sandbox Code Playgroud)