注意:这个问题与潜在的重复问题略有不同……而且这个问题的答案很有效——请在投票前阅读这两个问题:)。
--
我们有两个字典,它们的值具有共同的基类型:
代码如下:
// Three classes
class BaseClass {...}
class Foo : BaseClass {...}
class Bar : BaseClass {...}
// Two collections
var fooDict = new Dictionary<long, Foo>;
var barDict = new Dictionary<long, Bar>;
// One method
public void FooBar (Dictionary<long, BaseClass> dict) {...}
// These do not work
FooBar(fooDict);
FooBar(barDict);
有没有一种方法可以让继承在字典中起作用,或者我们是否必须使用不同的范例——或者我只是太蠢了?
如有任何帮助或指导,我们将不胜感激。
提前谢谢你。
诀窍是使方法通用并通过 where 关键字限制类型。
试试这个:
namespace GenericsTest
{
using System;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
Program p = new Program();
p.Run();
Console.In.ReadLine();
}
private void Run()
{
Dictionary<long, Foo> a = new Dictionary<long, Foo> {
{ 1, new Foo { BaseData = "hello", Special1 = 1 } },
{ 2, new Foo { BaseData = "goodbye", Special1 = 2 } } };
Test(a);
}
void Test<Y>(Dictionary<long, Y> data) where Y : BaseType
{
foreach (BaseType x in data.Values)
{
Console.Out.WriteLine(x.BaseData);
}
}
}
public class BaseType { public string BaseData { get; set; } }
public class Foo : BaseType { public int Special1 { get; set; } }
public class Bar : BaseType { public int Special1 { get; set; } }
}
输出:
hello
goodbye