【发布时间】:2011-04-05 15:05:47
【问题描述】:
可能重复:
Solution for overloaded operator constraint in .NET generics
我正在处理一个问题,目前它适用于 ints,但我希望它适用于可以使用 + 运算符添加的所有类。有没有办法在泛型中定义它?例如,
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 接口的依赖注入实例。由于运算的性质是数学的,因此 OutputType 通常是双倍的。
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);
这样所有操作都在编译时执行:)
享受吧!
【问题讨论】:
-
不,不直接。但是有一篇关于 CodeProject 的文章模拟了这一点。
-
感谢您的回复。你能给我一个解决方案的链接吗?
-
为什么没有 ISummable
中可以添加两个 T 的方法,例如 T Add(T first, T second)?使用 + 运算符进行加法将 IMO 涉及反射调用 op_Addition 方法。 -
@Timwi:除了动态会慢很多。所以它并没有过时。
-
@TerrorAustralis:如果我手头有网址,我会发布的。我记得几年前看到它的事实并不意味着我仍然拥有该链接。