我正在執行一些類型(在下面的示例中爲MyType
),它具有Collection
屬性。 MyType
我真的不在乎這是什麼樣的集合。我唯一關心的是它實現了IEnumerable<String>
和INotifyCollectionChanged
。我將如何實施Collection
財產與這些限制?接口繼承是否在這裏做正確的事情,爲什麼它不起作用?
這裏是我試過:
我創建了一個新的接口:
interface INotifyEnumerableCollectionChanged<T> : IEnumerable<T>, INotifyCollectionChanged {}
和INotifyEnumerableCollectionChanged<String>
型MyType
作出Collection
財產。這似乎在MyType
內工作。看起來我可以列舉該集合並註冊CollectionChanged
事件。
但我無法將此屬性設置爲集合(在下面的示例中爲MyCollection
),即使是艱難的MyCollection
也實現了IEnumerable<String>
和INotifyCollectionChanged
。
編譯器說:
無法隱式轉換類型 'InterfaceInheranceTest.Program.MyCollection' 到 'InterfaceInheranceTest.Program.INotifyEnumerableCollectionChanged'。 的顯式轉換存在(是否缺少 投?)
什麼是做到這一點的正確方法?
以下是完整的示例代碼:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Specialized;
namespace InterfaceInheranceTest
{
class Program
{
interface INotifyEnumerableCollectionChanged<T> : IEnumerable<T>, INotifyCollectionChanged {}
class MyCollection : IEnumerable<String>, INotifyCollectionChanged
{
IEnumerator<String> IEnumerable<String>.GetEnumerator()
{ throw new NotImplementedException(); }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{ throw new NotImplementedException(); }
public event NotifyCollectionChangedEventHandler CollectionChanged;
}
class MyType
{
private INotifyEnumerableCollectionChanged<String> _Collection;
public INotifyEnumerableCollectionChanged<String> Collection
{
get { return _Collection; }
set
{
_Collection = value;
_Collection.CollectionChanged += new NotifyCollectionChangedEventHandler(_Collection_CollectionChanged);
foreach (var item in _Collection)
{
Console.WriteLine(item);
}
}
}
void _Collection_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{ throw new NotImplementedException(); }
}
static void Main(string[] args)
{
var collection = new MyCollection();
var type = new MyType();
type.Collection = collection; // compiler doesn't like this!
}
}
}
好的,編譯。但爲什麼這需要?它已經實現了'IEnumerable'和'INotifyCollectionChanged'。而'INotifyEnumerableCollectionChanged '並不真正給他們添加任何東西。 –
2011-12-22 10:03:49
@RobertHegner - 你正在定義你正在使用的變量的類型是'INotifyEnumerableCollectionChanged'。您的實現不會實現此接口,因此不能用作對其的有效引用。 –
Oded
2011-12-22 10:04:57
好的謝謝你的解決方案和解釋!我會在4分鐘內接受... :) – 2011-12-22 10:07:15