【问题标题】:c# overrides method with dictionary that has base type [duplicate]c#用具有基本类型的字典覆盖方法[重复]
【发布时间】:2014-12-27 14:24:06
【问题描述】:

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

--

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

代码如下:

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

有没有办法让继承在字典中工作,或者我们必须使用不同的范例 - 还是我只是愚蠢?

对此的任何帮助或指导将不胜感激。

提前谢谢你。

【问题讨论】:

  • 所以这不是设计使能的——因为这样做是不安全的……我会在下面看看 wavy 的回答
  • 未来读者的注意事项 - 以下来自 WavyDavy 和 HimBromBreere 的两个很好的解决方案 - 都检查一下

标签: c# inheritance dictionary


【解决方案1】:

诀窍是使方法通用并通过 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

【讨论】:

  • 现在这么聪明......安全吗?
  • 如果您的解决方案提供相同的名称会更好。不管多么好:)
【解决方案2】:
public void FooBar<T> (Dictionary<long, T> dict) where T : BaseClass {...}

编辑:另一种方法是让FooBar 实现相同的接口。然后你可以在没有通用的东西的情况下做到这一点:

interface IFoo {}
class Foo : IFoo {}
class Bar : Bar {}

public void FooBar(Dictionary<long, IFoo> dict) {...}

【讨论】:

  • 很好,但 Wavy 最先到达那里 ;)
  • 更整洁。更具可读性。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-03-14
  • 1970-01-01
  • 1970-01-01
  • 2021-01-27
  • 2012-11-15
  • 2023-03-08
  • 1970-01-01
相关资源
最近更新 更多