c# - 转换一个实现接口(interface)中所有方法的类

标签 c# unit-testing casting polymorphism

如果一个类碰巧实现了一个接口(interface)中的所有方法(但没有显式实现它),是否有办法将该类的实例转换为该接口(interface)?

为了演示这个问题,我设置了以下简单类。 Scavenger 是我要进行单元测试的演示

IFinder interface 可以通过dictionary 实现(或者可以通过其他方式实现)。 Finder 是使用字典处理提升的接口(interface)示例实现。

//System under test
public class Scavenger
{
    private readonly IFinder _lookup;

    public Scavenger(IFinder lookup)
    {
        _lookup = lookup;
    }

    public string WhatIs(string key)
    {
        if (_lookup.ContainsKey(key)) return _lookup[key];
        return null;
    }
}

//Interface that can be met by a dictionary
public interface IFinder
{
    bool ContainsKey(string key);
    string this[string key] { get; set; }
}


//Implement IFinder using a dictionary
public class Finder : Dictionary<string,string>, IFinder
{
    public Finder()
    {
        this.Add("A","Hello");
        this.Add("B","Goodbye");
    }
}

我希望能够按照这些思路为 Scavenger 设置测试...

    /// <summary>
    /// This will fail because due to failed cast a Dictionary to an IFinder
    /// </summary>
    [TestMethod]
    public void LookupUsingDictionary()
    {
        var dic = new Dictionary<string, string>();
        dic.Add("A","B");
        var scavenger = new Scavenger(dic as IFinder);
        var res = scavenger.WhatIs("A");
        Assert.AreEqual("B", res);
    }

问题是 (dic as IFinder) == null。我知道我可以设置一个类似于 Finder 的模拟类,或者使用一个模拟框架,但我只是想检查我是否缺少某种转换字典来完成这项工作的方法

最佳答案

当您有一个接口(interface)和一个实现了所有适当方法但没有实现该接口(interface)的类时,您可以使用适配器模式来实现您的目标。创建一个实现给定接口(interface)并接受具有所有所需方法的类型的实例的类。然后它可以将所有方法重定向到组合类:

public class DictionaryFinder : IFinder
{
    private Dictionary<string, string> dictionary;
    public DictionaryFinder(Dictionary<string, string> dictionary)
    {
        this.dictionary = dictionary;
    }


    public bool ContainsKey(string key)
    {
        return dictionary.ContainsKey(key);
    }

    public string this[string key]
    {
        get { return dictionary[key]; }
        set { dictionary[key] = value; }
    }
}

这允许你写:

var scavenger = new Scavenger(new DictionaryFinder(dic));

关于c# - 转换一个实现接口(interface)中所有方法的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21586015/

相关文章:

c# - Visual Studio 版本不可知的项目/解决方案 : is it possible?

c# - 静态字段 - 使用静态的字符串插值

c++ - 计算器.cpp :48:24: error: invalid conversion from 'char' to 'const char*' [-fpermissive]

c# - 从另一个数据表更新数据表中数据的有效方法

unit-testing - Symfony2登录FOS UserBundle进行功能测试

java - 是否可以只运行一个测试类(利用 PowerMock 和 Mockito)?

.net - 有没有可以模拟静态方法和密封类的免费模拟框架?

c++ - float 转换 C++

Javascript Truthy/Falsy 操作

c# - 披萨、线程、等待、通知。这是什么意思?