Solution for overloaded operator constraint in .NET generics
我有一个问题,我的工作,目前正在为它工作
int
但是我希望它适用于所有可以使用
+
接线员。有没有办法在泛型中定义这一点?例如,
public List<T> Foo<T>() where T : ISummable
编辑:
传递一个委托来进行求和而不是使用Int类型的+=的性能最多慢540%。调查其他可能的解决方案
最终解决方案:
以函数的形式实现一个包含所有必需操作符的接口
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接口的依赖注入实例。输出类型通常是双精度的,因为操作的本质是数学的。
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);
这样,所有操作都在编译时强制执行:)
好好享受!