.NET equivalent for Java wildcard generics <?> with co- and contra- variance?

▼魔方 西西 提交于 2019-12-01 07:35:21

You need to translate the Java wildcard generic methods to C# methods that are generic in their own right. For example, this:

interface IGeneric2<T extends Impl> {
    void method2(IGeneric1<?> val);
}

should be translated to

interface IGeneric2<T>where T:Impl {
    void method2<U>(IGeneric1<U> val) where U:Impl;
}

It is necessary to repeat the type constraint for T specified by IGeneric1<T> as the type constraint for U.

The reason for this is that in the Java version there are implicit constraints for the type arguments of the parameters of method1 and method2: if the parameter must be some kind of IGeneric1<X> then X must obviously be an Impl because otherwise it could not possibly implement IGeneric1 for that type.

In C# the constraints must be explicit, so you repeat what IGeneric1<T> and IGeneric2<T> require of T.

So the equivalent code would be:

interface IInterf { }

class Impl : IInterf { }

interface IGeneric1<T> where T:Impl {
    void method1<U>(IGeneric2<U> val) where U:Impl;
    void method1WithParam(T to);
}

interface IGeneric2<T>where T:Impl {
    void method2<U>(IGeneric1<U> val) where U:Impl;
}

abstract class Generic<T> : IGeneric1<T>, IGeneric2<T> where T : Impl
{
    public void method1<U>(IGeneric2<U> val2) where U:Impl
    {
        val2.method2(this);
    }

    public abstract void method1WithParam(T to);
    public abstract void method2<U>(IGeneric1<U> val) where U:Impl;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!