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

前端 未结 1 1307
逝去的感伤
逝去的感伤 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 {
        void method2(IGeneric1 val);
    }
    

    should be translated to

    interface IGeneric2where T:Impl {
        void method2(IGeneric1 val) where U:Impl;
    }
    

    It is necessary to repeat the type constraint for T specified by IGeneric1 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 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 and IGeneric2 require of T.

    So the equivalent code would be:

    interface IInterf { }
    
    class Impl : IInterf { }
    
    interface IGeneric1 where T:Impl {
        void method1(IGeneric2 val) where U:Impl;
        void method1WithParam(T to);
    }
    
    interface IGeneric2where T:Impl {
        void method2(IGeneric1 val) where U:Impl;
    }
    
    abstract class Generic : IGeneric1, IGeneric2 where T : Impl
    {
        public void method1(IGeneric2 val2) where U:Impl
        {
            val2.method2(this);
        }
    
        public abstract void method1WithParam(T to);
        public abstract void method2(IGeneric1 val) where U:Impl;
    }
    

    0 讨论(0)
提交回复
热议问题