C# 可以隐藏继承的接口(interface)吗?

标签 c# .net generics inheritance interface

我有一组看起来像这样的接口(interface)和类:

public interface IItem
{
    // interface members
}
public class Item<T> : IItem
{
    // class members, and IItem implementation
}
public interface IItemCollection : IEnumerable<IItem>
{
    // This should be enumerable over all the IItems
}
// We cannot implement both IItemCollection and IEnumerable<TItem> at
// the same time, so we need a go between class to implement the
// IEnumerable<IItem> interface explicitly:
public abstract class ItemCollectionBase : IItemCollection
{
    protected abstract IEnumerator<IItem> GetItems();
    IEnumerator<IItem> IEnumerable<IItem>.GetEnumerator() { return GetItems(); }
    IEnumerator IEnumerable.GetEnumerator() { return GetItems(); }
}

public class ItemCollection<TKey, TItem> : ItemCollectionBase, IEnumerable<TItem>
    where TItem : class,IItem,new()
{
    private Dictionary<TKey, TItem> dictionary;
    protected override GetItems() { return dictionary.Values; }
    public IEnumerator<TItem> GetEnumerator() { return dictionary.Values; }
}

我遇到的问题是当我尝试在我的 ItemCollection 上使用 Linq 时,它变得困惑,因为有两个 IEnumerable 接口(interface)。

我收到以下错误消息:

无法从用法中推断方法“System.Linq.Enumerable.Where(...)”的类型参数。尝试明确指定类型参数。

有没有办法隐藏“更原始”的IEnumerable接口(interface),使其在处理ItemCollection<,>时总是选择IEnumerable,但在处理ItemCollection<,>时仍然提供IEnumerable接口(interface)IItemCollection接口(interface)?


(当我要发布这个时,我意识到有一个解决方法,可以像这样实现它:

public interface IItemCollection
{
    IEnumerable<IItem> Items { get; }
}

但是我还是想知道有没有办法隐藏一个界面。)

最佳答案

也许你可以通过一点组合而不是继承来实现你想要的:

public interface IItem
{
    // interface members
}
public class Item<T> : IItem
{
    // class members, and IItem implementation
}
public interface IItemCollection
{
    IEnumerable<IItem> GetItems();
}    
public class ItemCollection<TKey, TItem> : IItemCollection, IEnumerable<TItem>
    where TItem : class,IItem,new()
{
    private Dictionary<TKey, TItem> dictionary;
    public IEnumerator<TItem> GetEnumerator() { return dictionary.Values; }
    public IEnumerable<IItem> GetItems() { return dictionary.Values.Cast<IItem>(); }
}

我们可以改变IItemCollection以便它返回 IEnumerable<IItem>而不是实现 IEnumerable<IItem> .现在您的具体类可以实现所有接口(interface),您不需要抽象类。

关于C# 可以隐藏继承的接口(interface)吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25274274/

相关文章:

c# - 使用 ASP.Net C#、DropDownList 和重定向?

generics - 当您不关心返回值时,创建适应性强的泛型返回类型的首选方法是什么?

java - 为什么 Bounded 类型参数出现 "java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to"错误而不是 Formal 类型参数?

c# - 如何从一个方法返回多个值?

c# - 在 azure 网络应用程序中 File.Exists 返回 false 实际上文件存在

c# - 继承真的隐藏了方法吗?

.net - 使用 Windows 身份验证时如何模拟另一个 Windows 用户?

c# - 按顺序使用数组获取文件

c# - Visual Studio 线程窗口为空?

swift - 快速覆盖通用函数错误