繁体   English   中英

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

[英]C# generics: using class generic in where clause of method generic

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

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

...

A<K> obj = new A<K>();
obj.Method<J>();

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

我收到这个错误:

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

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

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

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

IEnumerable<Derived> d = new List<Derived>();
IEnumerable<Base> b = d;

它对我有用(VS 2008)。

课程可见性有问题吗? (类不公开,命名空间错误)

您收到了哪条错误消息?


UPDATE

鉴于您对Container<T>实现,我可以写

class A { }
class B : A { }

class Test
{
    public void MethodName( )
    {
        var obj = new Container<A>();
        obj.Set(new B());
    }
}

这非常有效。 你确定B来自A吗? 请注意,例如List<B>不是从List<A>派生的(参见YavgenyP的答案)。


错误消息可能是一个提示,告诉您在另一个命名空间中存在另一个Container<T> ,需要PerType<U, X??? >的第二个类型参数PerType<U, X??? > PerType<U, X??? >

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM