简体   繁体   中英

c# implicit casts of generic types

I'm trying to understand implicit casts on generic types. The following lines of codes won't compile:

class Dataset : Dictionary<string, string>
{
}

class Section : List<Dataset>
{
    public List<Dictionary<string, string>> ToBase()
    {
        return this;
    }
}

However, if I add the following implicit operator to the Section class they compile.

public static implicit operator List<Dictionary<string, string>>(Section section)
{
    return section;
}

What do these lines really change? (By the way: ReSharper now shows an "Conversion to base class" error, but I couldn't find anything about it.

Could anyone please explain to me what's going on here?? Thanks!!

You can't cast a List<Dataset> to a List<Dictionary<string, string>> , because List<T> isn't covariant (and only interfaces in C# can be covariant, so you would need a IList<T> , but IList<T> isn't covariant)

Note that this:

public IEnumerable<Dictionary<string, string>> ToBase()
{
    return this;
}

is legal, because IEnumerable<> is covariant, so you can cast a IEnumerable<subclass> to a IEnumerable<baseclass>

To give some examples:

Section section = new Section();

List<Dataset> sectionAsList = section; // Legal

List<Dictionary<string, string>> sectionAsListDictionary = section; // Illegal
IList<Dictionary<string, string>> sectionAsIListDictionary = section; // Illegal

IEnumerable<Dictionary<string, string>> sectionAsIEnumerableDictionary = section; // Legal

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