问题描述
有人可以解释为什么这行不通吗?无论数字类型如何,我都试图能够添加两个值.
Can someone explain why this won't work? I was trying to be able to add two values regardless of the numeric type.
public static T Add<T> (T number1, T number2)
{
return number1 + number2;
}
编译时出现以下错误:
Operator '+' cannot be applied to operands of type 'T' and 'T'
推荐答案
没有允许您强制执行运算符重载的通用约束.您可以查看以下库.或者,如果您使用 .NET 4.0,您可以使用 dynamic
关键字:
There is no generic constraint that allows you to enforce operator overload. You may take a look at the following library. Alternatively if you are using .NET 4.0 you could use the dynamic
keyword:
public static T Add<T>(T number1, T number2)
{
dynamic a = number1;
dynamic b = number2;
return a + b;
}
显然,这不适用任何编译时安全性,而这正是泛型的意义所在.应用编译时安全的唯一方法是强制执行通用约束.对于您的场景,没有可用的约束.这只是欺骗编译器的一个技巧.如果 Add 方法的调用者不传递使用 + 运算符的类型,则代码将在运行时抛出异常.
Obviously this doesn't apply any compile time safety which is what generics are meant for. The only way to apply compile time safety is to enforce generic constraints. And for your scenario there is no constraint available. It's only a trick to cheat the compiler. If the caller of the Add method doesn't pass types that work with the + operator the code will throw an exception at runtime.
这篇关于C# 添加两个泛型值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!