简体   繁体   English

一种实现通用和非通用接口的函数

[英]One function implementing Generic and non-generic interface

Lets say I have a class, which implements a generic interface public interface IItem {} 可以说我有一个类,该类实现了通用接口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. 我想让MyStuff类实现此IFavoriteItem接口。 Since TItem implements IItem it seems for me, that public TItem FavoriteItem property is implementing IFavoriteItem already. 由于TItem实现了IItem,在我看来, public TItem FavoriteItem属性已经实现了IFavoriteItem。

But compiler doesn't think so, and it wants me to declare a separate IItem IFavoriteItem.FavoriteItem in MyClass. 但是编译器不这么认为,它希望我在MyClass中声明一个单独的IItem IFavoriteItem.FavoriteItem Why is it so? 为什么会这样呢? Isn't c# covariance the thing that should play here and solve my problem? C#协方差不是应该在这里解决我的问题的东西吗?

Thanks 谢谢

The reason for this is that FavoriteItem of IFavoriteItem may not be IItem , where on the IFavoriteItem , it must be an IItem . 这样做的原因是, FavoriteItemIFavoriteItem可能不是 IItem ,其中在IFavoriteItem ,它必须是一个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. 这将简单地将对TItem实现的调用快捷方式化。

A good example of where this is used quite often is with the implementation of IEnumerable<> . IEnumerable<>的实现是一个经常使用此方法的好例子。 These often look like this: 这些通常看起来像这样:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM