c# - ObservableCollection 作为参数和接口(interface)传递

标签 c# interface observablecollection

我有一个界面IPerson和两个类(class),AdventurerWorker来实现它。我目前有单独的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/

相关文章:

c# - 以编程方式更改 Crystal Reports 对象可见性

c# - 通用接口(interface)和方法问题

C#性能: construct new collection with existing items using constructor or loop?

go - 如何让一个接口(interface)方法返回另一个接口(interface)?

c# - MVVM模式,ViewModel集合

java Swing——JPanel 和 PropertyChangeListener

c# - 在播放nAudio时绘制.wav文件

c# - EntityState 修改后的 SaveChanges 不保存

javascript - 如何使用 C# 代码添加 Html Audio 元素

go - 对接口(interface)进行类型断言,内部发生了什么