简体   繁体   中英

How to covariant/contravariant in override virtual method which implements from interface?

I want to do contravariance in override virtual method which implements from interface, I had try both ICloneTo<in T> and ICloneTo<out T> all getting compile errors, as the following code:

interface ICloneTo<T> {
    void CloneTo(T obj);
}

abstract class Base : ICloneTo<Base> {
    public string BaseProperty { get; set; }

    public virtual void CloneTo(Base obj) {
        obj.BaseProperty = BaseProperty;
    }
}

class A : Base {
    public string AProperty { get; set; }

    public override void CloneTo(A obj /* Contravariance to A */) {
        base.CloneTo(obj);
    
        obj.AProperty = AProperty;
    }
}

There is no parameter contra-variance for method overriding in C# at this time.

This is the closest to a discussion on it I have found: https://github.com/do.net/csharplang/discussions/3562

However, with some generic finagling, you can come up with:

    interface ICloneTo<T>
    {
        void CloneTo(T obj);
    }

    abstract class Base<T> : ICloneTo<T>
        where T : Base<T>
    {
        public string BaseProperty { get; set; }

        public virtual void CloneTo(T obj)
        {
            obj.BaseProperty = BaseProperty;
            throw new NotImplementedException();
        }
    }

    class A : Base<A>
    {
        public string AProperty { get; set; }

        public override void CloneTo(A obj /* Contravariance to A */)
        {
            base.CloneTo(obj);

            obj.AProperty = AProperty;
        }
    }

Though there are probably better ways to solve whatever problem you're trying to solve...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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