C#添加两个通用值 [英] C# Adding two Generic Values

查看:187
本文介绍了C#添加两个通用值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以解释为什么这不会工作吗?我试图能够添加两个值,而不管数字类型。

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;
}

当我编译这个,我得到以下错误:

When I compile this, I get the following error:

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


推荐答案

没有通用约束允许您强制运算符重载。您可以查看下列库。或者,如果您使用.NET 4.0,您可以使用动态关键字:

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#添加两个通用值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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