c使用具有基类型的字典重写方法



注意:这个问题与潜在的重复有细微的不同。。。这是有效的答案——请在投票前阅读:)。

--

我们有两个字典,它们的值有一个共同的基类型:

这是代码:

// 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
public void FooBar<T> (Dictionary<long, T> dict) where T : BaseClass {...}

EDIT:另一种方法是让FooBar实现相同的接口。然后你就可以不用通用的东西:

interface IFoo {}
class Foo : IFoo {}
class Bar : Bar {}
public void FooBar(Dictionary<long, IFoo> dict) {...}

最新更新