通用的方法来添加整数,浮点,在C# [英] generic method to add int, float, in c#
问题描述
我写一个通用的方法,除了整数,浮点型,双
public T Swap<T>( T value1, T value2)
{
T temp;
temp = value1 +value2;
return temp;
}
我得到一个错误:
I am getting an error:
运算符'+'不能应用于类型为'T'和'T'的操作数
我使用VS 2005 ,谁能告诉我怎么才达到的?
I am using VS 2005, can anyone tell me how to achive it?
推荐答案
您不能直接做到这一点。在.NET泛型只是不支持它。不过,也有其他的选择:
You can't do this directly. Generics in .NET just don't support it. However, there are other options available:
-
在C#4,你可以使用动态类型:
In C# 4, you can use dynamic typing:
public static T Sum<T>(T value1, T value2)
{
dynamic temp = value1;
temp += value2;
return temp;
}
编辑:我没有注意到你正在使用VS2005。你真的有无的到?任何机会,你可以升级到一些更近期的?
I hadn't noticed that you were using VS2005. Do you really have to? Any chance you could upgrade to something a little more recent?
马克Gravell中的 MiscUtil 与代表要做到这一点非常有效。请参阅使用页面了解更多信息。在MiscUtil实现使用C#3和.NET 3.5,但我相信马克拥有的独立的实施在.NET 2同样的想法使用 DynamicMethod的
。我们可以ping他来检查,如果你需要的...
Marc Gravell wrote code in MiscUtil to do this pretty efficiently with delegates. See the usage page for more information. The implementation in MiscUtil uses C# 3 and .NET 3.5, but I believe Marc has a separate implementation of the same ideas in .NET 2 using DynamicMethod
. We can ping him to check if you need that...
这篇关于通用的方法来添加整数,浮点,在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!