本文介绍了一个实现通用和非通用接口的功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个类,它实现了一个通用接口
public interface IItem {}

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

我还有一个非通用接口

public interface IFavoriteItem
{
    IItem FavoriteItem { get; }
}

我想让MyStuff类实现这个IFavoriteItem接口。由于TItem实现了IItem,对我来说, public TItem FavoriteItem 属性已经实现了IFavoriteItem。

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.

但是编译器没有不这么认为,它要我在MyClass中声明一个单独的 IItem IFavoriteItem.FavoriteItem 。为什么会这样? c#covariance不是应该在这里玩并解决我的问题吗?

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?

谢谢

推荐答案

原因是 FavoriteItem IFavoriteItem 可能不会 IItem ,在 IFavoriteItem 上,必须的iItem 。解决这个问题的唯一方法是:

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

这只会简化对 TItem的调用实现。

经常使用它的一个很好的例子是 IEnumerable<> 。这些通常如下所示:

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

这篇关于一个实现通用和非通用接口的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 09:31