通用 C# 代码和 Plus 运算符 [英] Generic C# Code and the Plus Operator
问题描述
我正在编写一个类,该类对 C# 中的每个基本数字类型执行基本相同类型的计算.虽然实际计算更复杂,但可以将其视为一种计算多个值的平均值的方法,例如
I'm writing a class that does essentially the same type of calculation for each of the primitive numeric types in C#. Though the real calculation is more complex, think of it as a method to compute the average of a number of values, e.g.
class Calc
{
public int Count { get; private set; }
public int Total { get; private set; }
public int Average { get { return Count / Total; } }
public int AddDataPoint(int data)
{
Total += data;
Count++;
}
}
现在为了支持 double、float 和其他定义运算符 + 和运算符/的类的相同操作,我的第一个想法是简单地使用泛型:
Now to support that same operation for double, float and perhaps other classes that define operator + and operator /, my first thought was to simply use generics:
class Calc<T>
{
public T Count { get; private set; }
public T Total { get; private set; }
public T Average { get { return Count / Total; } }
public T AddDataPoint(T data)
{
Total += data;
Count++;
}
}
不幸的是,C# 无法确定 T 是否支持运算符 + 和/所以不编译上面的代码片段.我的下一个想法是将 T 限制为支持这些运算符的类型,但我最初的研究表明这是不可能的.
Unfortunately C# is unable to determine whether T supports operators + and / so does not compile the above snippet. My next thought was to constrain T to types that support those operators, but my initial research indicates this cannot be done.
当然可以在实现自定义接口的类中装箱我想要支持的每种类型,例如IMath 并将 T 限制在这一点上,但是这段代码将被调用很多次,我想避免装箱开销.
It's certainly possible to box each of the types I want to support in a class that implements a custom interface e.g. IMath and restrict T to that, but this code will be called a great number of times and I want to avoid boxing overhead.
有没有一种优雅有效的方法可以在不重复代码的情况下解决这个问题?
Is there an elegant and efficient way to solve this without code duplication?
推荐答案
我最终使用了表达式,这是 Marc Gravell 概述的一种方法,我通过点击 Spinon 评论中的链接找到了该方法.
I ended up using Expressions, an approach outlined by Marc Gravell that I found by following links off of spinon's comment.
https://jonskeet.uk/csharp/miscutil/usage/genericoperators.html
这篇关于通用 C# 代码和 Plus 运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!