<分区>
Possible Duplicate:
Solution for overloaded operator constraint in .NET generics
我正在处理一个问题,目前它正在为 int
工作,但我希望它能为所有可以使用 +
添加的类工作运算符(operator)。有没有办法在通用中定义它?例如,
public List<T> Foo<T>() where T : ISummable
有什么办法吗?
编辑:
传递一个委托(delegate)来进行求和而不是使用 += 和 Int 类型的性能最多慢 540%。研究可能的其他解决方案
最终解决方案:
谢谢大家的建议。我最终得到了一个不太慢的解决方案,并在编译时强制执行检查。我不能完全相信这是一位同事帮助我得出的结论。无论如何,这里是:
以函数的形式实现一个接口(interface),其中包含所有必需的运算符
public interface IFoo<InputType, OutputType>
{
//Adds A to B and returns a value of type OutputType
OutputType Add(InputType a, InputType b);
//Subtracts A from B and returns a value of type OutputType
OutputType Subtract(InputType a, InputType b);
}
创建您要定义的类,但不要使用 Where 子句,而是使用 IFoo 接口(interface)的依赖注入(inject)实例。 OutputType 通常是 double,因为操作的性质是数学的。
public class Bar<T>
{
private readonly IFoo<T,double> _operators;
public Bar(IFoo<T, double> operators)
{
_operators = operators;
}
}
现在当你使用这个类时,你定义操作规则如下:
private class Foo : IFoo<int, double>
{
public double Add(int a, int b)
{
return (double)(a+b);
}
public double Subtract(int a, int b)
{
return (double)(a-b);
}
}
然后你会像这样使用它:
Foo inttoDoubleOperations = new Foo();
Bar myClass = new Bar(Foo);
这样所有操作都在编译时强制执行:)
尽情享受吧!