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

前端 未结 1 1319
逝去的感伤
逝去的感伤 2021-01-14 03:19

I\'m stuck trying to translate some Java code that uses (bounded) wildcard generics to C#. My problem is, Java seems to allow a generic type to be both covariant and contr

相关标签:
1条回答
  • 2021-01-14 03:29

    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;
    }
    
    0 讨论(0)
提交回复
热议问题