One function implementing Generic and non-generic interface

扶醉桌前 提交于 2019-12-11 17:02:39

问题


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


回答1:


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();
    }
}


来源:https://stackoverflow.com/questions/4049702/one-function-implementing-generic-and-non-generic-interface

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!