如何计算C#中的通用数字? [英] How to sum generic numbers in C#?

查看:65
本文介绍了如何计算C#中的通用数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能存在重复:






正如你在下面的代码中看到的那样,我需要计算两个通用数字的总和。

  public class NumberContainer< T> 
{
public T ValueA {get;私人设置; }
public T ValueB {get;私人设置; }
public T Total {get {return ValueA + ValueB; }}
}

然而,不可能直接添加两个T值,这会导致编译器错误如下:

lockquote

运算符'+'不能应用于'T'类型的操作数和' T'

鉴于我不打算将T用于除表示数字的值类型(short,ushort, int,uint等),我怎么能执行这个和? (效率是一个需要考虑的因素)

你可以用LINQ的小魔术来做:

  private static readonly Func< T,T,T>加法器; 
static NumberContainer(){
var p1 = Expression.Parameter(typeof(T));
var p2 = Expression.Parameter(typeof(T));
adder =(Func )表达式
.Lambda(Expression.Add(p1,p2),p1,p2)
.Compile();
}
public T Total {get {return adder(ValueA,ValueB); }}

唯一的缺点是这段代码编译,即使 NumberContainer 使用不支持加法的类型 T 进行实例化;当然它会在运行时抛出异常。另外一个好处是,这个应该用于用户定义的 + 运算符。


Possible Duplicate:
C# generic constraint for only integers

As you can see in the following code, I need to compute the sum of two generic numbers.

public class NumberContainer<T>
{
    public T ValueA { get; private set; }
    public T ValueB { get; private set; }
    public T Total { get { return ValueA + ValueB; } }
}

However, it isn't possible to do a direct addition of the two T values, which results in the compiler error below :

Operator '+' cannot be applied to operands of type 'T' and 'T'

Given that I don't intend to use T for anything else than value-types that represent numbers (short, ushort, int, uint, etc), how could I perform the sum? (efficiency is a factor to be considered)

解决方案

You can do it with "little magic" from LINQ:

private static readonly Func<T, T, T> adder;
static NumberContainer() {
    var p1 = Expression.Parameter(typeof (T));
    var p2 = Expression.Parameter(typeof (T));
    adder = (Func<T, T, T>)Expression
        .Lambda(Expression.Add(p1, p2), p1, p2)
        .Compile();
} 
public T Total { get { return adder(ValueA, ValueB); } }

The only drawback is that this code will compile even if NumberContainer is instantiated with a type T that does not support addition; of course it will throw an exception at run-time. An added benefit is that this should work with user-defined + operators.

这篇关于如何计算C#中的通用数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆