c# 用具有基类型的字典覆盖方法

标签 c# inheritance dictionary

<分区>

注意:这个问题与潜在的重复问题略有不同……而且这个问题的答案很有效——请在投票前阅读这两个问题:)。

--

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

代码如下:

// 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

关于c# 用具有基类型的字典覆盖方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26671733/

相关文章:

c# - 如何使用 MVC 在同一个 Controller 中复制一个 Action

javascript - 绑定(bind) gridview 时在进程中抛出错误?

c++ - 如何在 JSON 中标记对象的继承?

c++ - 为派生类提供模板特化的最简单方法

c# - 什么 C# 功能允许使用 "object literal"类型表示法?

c# - 没有配置文件的 WCF/服务引用

c# - 配置 HttpClientFactory 时证书错误

c++ - 基类有不完整的类型

c# - 自动字典键?

C++常量混淆