简体   繁体   中英

One function implementing Generic and non-generic interface

Lets say I have a class, which implements a generic interface public interface IItem {}

public interface IStuff<out TItem> where TItem : IItem
{
    TItem FavoriteItem { get; }
}

public class MyStuff<TItem> : IStuff<TItem> where TItem : IItem
{
    public TItem FavoriteItem
    {
        get { throw new NotImplementedException(); }
    }
}

I have also one non-generic interface

public interface IFavoriteItem
{
    IItem FavoriteItem { get; }
}

I'd like to make MyStuff class implement this IFavoriteItem interface. Since TItem implements IItem it seems for me, that public TItem FavoriteItem property is implementing IFavoriteItem already.

But compiler doesn't think so, and it wants me to declare a separate IItem IFavoriteItem.FavoriteItem in MyClass. Why is it so? Isn't c# covariance the thing that should play here and solve my problem?

Thanks

The reason for this is that FavoriteItem of IFavoriteItem may not be IItem , where on the IFavoriteItem , it must be an IItem . The only way to solve this is by:

IItem IFavoriteItem.FavoriteItem
{
    get { return FavoriteItem; }
}

This will simply shortcut the call to your TItem implementation.

A good example of where this is used quite often is with the implementation of IEnumerable<> . These often look like this:

public class MyEnumerable : IEnumerable<T>
{
    public IEnumerator<T> GetEnumerator()
    {
        throw new NotImplementedException();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
}

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