开发者

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(); }
    }
}
开发者_StackOverflow社区

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜