Bry*_*ner 6 .net c# generics inheritance 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; }
}
Run Code Online (Sandbox Code Playgroud)
我遇到的问题是当我尝试在我的ItemCollection上使用Linq时,它会因为有两个IEnumerable接口而感到困惑.
我收到以下错误消息:
无法从用法推断出方法'System.Linq.Enumerable.Where(...)的类型参数.尝试显式指定类型参数.
有没有办法隐藏"更原始"的IEnumerable <IItem>接口,所以它在处理ItemCollection <,>时总会选择IEnumerable <TItem>,但在处理IItemCollection接口时仍然提供IEnumerable <IItem>接口?
(正如我即将发布的那样,我意识到有一种解决方法,就像这样实现它:
public interface IItemCollection
{
IEnumerable<IItem> Items { get; }
}
Run Code Online (Sandbox Code Playgroud)
但是我仍然想知道是否有隐藏界面的方法.)
也许你可以通过一点组合而不是继承来实现你想要的:
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>(); }
}
Run Code Online (Sandbox Code Playgroud)
我们可以进行更改IItemCollection
,使其返回 anIEnumerable<IItem>
而不是实现IEnumerable<IItem>
. 现在您的具体类可以实现所有接口,并且不需要抽象类。
归档时间: |
|
查看次数: |
767 次 |
最近记录: |