[英]How do I write an adapter class to simulate an interface on primitive types?
我有一个采用接口的方法。 我为每种原始类型(和字符串)写了一个自定义函数。 看起来是这样的:
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()方法签名的情况下无法做到这一点。 我不希望用户必须先创建一个适配器,而是希望它隐式发生。 有什么办法吗?
谢谢!
我可能会误会您,但是您可以这样做吗? 希望这不是您要避免的事情...您必须为每个原语编写一个适配器,但是至少您能够执行集合
public inteface IFoo
{
void DoSomething();
}
public IntFoo : IFoo
{
private int _value;
public IntFoo(int value)
{
_value = value;
}
void DoSomething()
{
IntDoSomething(_value);
}
}
我想到了两个选择:
一种方法是让DoSomething获取一个对象,以便任何值都可以使用,并且您可以在参数上使用“ is”运算符来确定类型。 这显然不是很安全的类型安全。
而且,正如您提到的,您可以将DoSomething设为通用函数。 然后,在实现中,您可以使用:
public void Execute<T>( T value)
{
if( value is int )
{
IntDoSomething();
}
else if( value is float)
{
FloatDoSomething();
}
}
等等
同样,它不是非常安全的类型,因此您可能想验证方法顶部的输入。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.