简体   繁体   中英

Generic inheritance with constraint conversion

The Error

The problem is with "hashset.Add(toAdd);"

CS1503: Argument 1: cannot convert from 'A<U>' to 'A<B>'

The Code

public interface B { }

public class A<T> where T : B { }

public class Test
{
    // Trying to add to this set
    HashSet<A<B>> hashset = new HashSet<A<B>>();

    public void AddToStack<U>(A<U> toAdd) where U : B
    {
        hashset.Add(toAdd);
    }
}

Other

I have to use U because there are other classes that inherit from B and I want to be able to accept those into the "AddToStack" method.

Class A has a constraint that any "T" will inherit from a B, and I am puzzled why it cannot automatically convert it with data loss. I understand that I can add a public static implicit operator to manually tell it how to convert, but I would like to understand why it cannot do it without defining the operation.

I am clearly in need of sleep. Thanks for the replies, Charlieface's 1 liner clued me in why I am wrong.

Corrected Code

public class A<T> where T : B { }

public interface B { }

public class Test<U> where U : B
{
    // Trying to add to this set
    HashSet<A<U>> hashset = new HashSet<A<U>>();

    public void AddToStack(A<U> toAdd)
    {
        hashset.Add(toAdd);
    }
}

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