简体   繁体   English

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

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

Can anyone explain why isn't this possible (at least in .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>();

with K being the superclass of J K是J的超类

EDIT 编辑

I've tried to simplify the problem in order to make the question more legible, but I've clearly overdo that. 我试图简化问题以使问题更清晰,但我显然已经过头了。 Sorry! 抱歉!

My problem is a little more specific I guess. 我想我的问题更具体一点。 This is my code (based on this ): 这是我的代码(基于 ):

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

and I'm getting this error: 我收到这个错误:

Container.cs(13,24): error CS0305: Using the generic type Container<T>.PerType<U>' requires 2' type argument(s) Container.cs(13,24):错误CS0305:使用泛型类型Container<T>.PerType<U>' requires 2'类型参数

Actually it is possible. 实际上这是可能的。 This code compiles and runs just fine: 这段代码编译并运行得很好:

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

What is not possible is using covariance / contravariance in generics, as explained here : 什么是不可能的使用仿制药协方差/逆变,为解释在这里

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

It works for me (VS 2008). 它对我有用(VS 2008)。

Do you have a problem with a class visibility? 课程可见性有问题吗? (class not public, wrong namespace) (类不公开,命名空间错误)

Which error message are you getting? 您收到了哪条错误消息?


UPDATE UPDATE

Given your implementation of Container<T> I can write 鉴于您对Container<T>实现,我可以写

class A { }
class B : A { }

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

This works perfectly. 这非常有效。 Are you sure that B derives from A ? 你确定B来自A吗? Note that for instance List<B> does NOT derive from List<A> (see YavgenyP's answer). 请注意,例如List<B>不是从List<A>派生的(参见YavgenyP的答案)。


The error message could be a hint, telling you that there exists another Container<T> in another namespace requiring a second type argument for PerType<U, X??? > 错误消息可能是一个提示,告诉您在另一个命名空间中存在另一个Container<T> ,需要PerType<U, X??? >的第二个类型参数PerType<U, X??? > PerType<U, X??? > . PerType<U, X??? >

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

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