我有一个界面IPerson
和两个类(class),Adventurer
和Worker
来实现它。我目前有单独的ObservableCollection
s 代表冒险家和 worker 。我有一个方法,我希望能够传递 ObservableCollection<Adventurer>
和一个ObservableCollection<Worker>
to 作为参数,到目前为止我还没有任何运气。该方法仅使用 IPerson
中实现的属性如果我将其声明为:
public void MyMethod(ObservableCollection<IPerson> collection)
...方法本身没有错误。但是,当我尝试传递 ObservableCollection<Adventurer>
时,我收到 2 个错误:
Cannot convert from 'System.Collections.ObjectModel.ObservableCollection' to 'System.Collections.ObjectModel.ObservableCollection'`
和
The best overloaded method match for 'AoW.MyMethod(System.Collections.ObjectModel.ObservableCollection)' has some invalid arguments`
我可以同时通过ObservableCollection
吗?是用同样的方法吗?如果是这样,我该怎么办?任何建议将不胜感激。
最佳答案
.NET 中的类不支持 covariance and contravariance 。只有接口(interface)可以。想象一下这个场景:
class Adventurer : IPerson { }
class NPC : IPerson { }
public void MyMethod(ObservableCollection<IPerson> collection)
{
collection.Add(new NPC());
}
var collectionOfAdventurers = new ObservableCollection<Adventurer>();
MyMethod(collectionOfAdventurers);
这显然会引发一些错误,因为传入的类型是 Adventurer
集合,但该方法添加了 NPC
,但这无法在编译时验证。因此,编译器不允许这种不安全行为,而是要求传入的类型必须与签名中的类型完全匹配,并且如果您尝试传入其他任何内容,则会给出错误。
我建议将 MyMethod
更改为:
public void MyMethod(IEnumerable<IPerson> enumerable)
或者
public void MyMethod(INotifyCollectionChanged collection)
具体取决于您需要访问哪些成员。
您可能还想考虑通用方法:
public void MyMethod<T>(ObservableCollection<T> collection) where T : IPerson
关于c# - ObservableCollection 作为参数和接口(interface)传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18292195/