如何编写适配器类来模拟基本类型的接口?

时间:2015-07-09 22:10:28

标签: c# oop design-patterns interface adapter

我有一个接受接口的方法。我为每个基本类型(和字符串)写了一个自定义函数。这是它的样子:

public interface IFoo
{
    void DoSomething();
}

static void IntDoSomething(int value)
{
    // do something with an int, as if it implemented IFoo
}

static void FloatDoSomething(float value)
{
    // do something with a float, as if it implemented IFoo
}

// ... I have an XDoSomething() for all the other primitives and string

public void Execute(IFoo value)
{
    value.DoSomething();
}

public void Execute(int value)
{
    IntDoSomething();
}

public void Execute(float value)
{
    FloatDoSomething();
}
// ... I have an Execute() for all the other primitives and string

虽然单调乏味,但每个基本类型都有一个Execute()是可行的。问题是当我必须添加这样的东西时:

public void Execute(List<IFoo> values)
{
    foreach (IFoo foo in values)
    {
        values.DoSomething();
    }
}

public void Execute(Dictionary<IFoo, IFoo> values)
{
    foreach (var pair in values)
    {
        pair.Key.DoSomething();
        pair.Value.DoSomething();
    }
}

每次我想要处理的新集合时,是否必须写出Execute()函数?对于字典一,我必须为每个原语的每个组合明确定义版本!

我觉得有一个解决方案涉及编写一个将基元包装为IFoos的适配器类,但是如果不破坏Execute()的方法签名,我似乎无法做到这一点。我不希望用户必须首先创建一个适配器,我希望它隐式发生。有没有办法做到这一点?

谢谢!

2 个答案:

答案 0 :(得分:0)

我可能会误解,但你可以这样做吗?希望这不是你想要避免的......你必须为每个原语编写一个适配器,但至少你能够执行你的集合执行

public inteface IFoo
{
    void DoSomething();
}

public IntFoo : IFoo
{
    private int _value;

    public IntFoo(int value)
    {
        _value = value;
    }

    void DoSomething()
    {
        IntDoSomething(_value);
    }
}

答案 1 :(得分:0)

我想到两个选择;

有人会让DoSomething获取一个对象以便任何值都可以工作,并且可以在参数上使用“is”运算符来确定类型。这显然不是很安全。

另外,正如您所提到的,您可以将DoSomething作为通用功能。然后,在实现中您可以使用:

public void Execute<T>( T value) 
{
    if( value is int )
    {
        IntDoSomething();
    }
    else if( value is float)
    {
        FloatDoSomething();
    }
}

同样,不是非常类型安全,因此您可能希望验证方法顶部的输入。