我有一组看起来像这样的接口(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
(当我要发布这个时,我意识到有一个解决方法,可以像这样实现它:
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/