如何将“Dictionary <x,class>”传递为Dictionary <x,interface>“?</x,interface> </x,class>

时间:2015-04-04 01:59:23

标签: c# generics interface

C#和Stackoverflow都是新手......请随时注明是否应该以不同的方式或其他地方提出要求。

假设:

public interface IPoint {...}
public struct DeliveryPoint : IPoint {...}

和生成具有大量交付点的字典的代码:

...
Dictionary<uint,DeliveryPoint> dict = new Dictionary<uint,DeliveryPoint>();
...

现在需要将这些点传递给需要接口类型的例程:

public void doSomething( Dictionary<uint,IPoint> dict ) { ...}

我以为我能够做到这样的事情:

doSomething( dict );

我找到的唯一解决方案是创建一个新的List并复制所有的点,这些点似乎首先破坏了实现接口的全部目的。

有更好的方法吗?

1 个答案:

答案 0 :(得分:3)

使方法通用于类型实现接口的值。

public void DoSomething<TPoint>(IDictionary<uint, TPoint> dict) where TPoint : IPoint
{
    // do stuff
}