开发者

generic method to add int, float, in c#

I am writing a 开发者_开发技巧generic method for addition of integers, float, double

public T  Swap<T>( T value1,  T value2)
{
    T temp;
    temp = value1 +value2;
    return temp;
}

I am getting an error:

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

I am using VS 2005, can anyone tell me how to achive it?


You can't do this directly. Generics in .NET just don't support it. However, there are other options available:

  • In C# 4, you can use dynamic typing:

    public static T Sum<T>(T value1,  T value2)
    {
        dynamic temp = value1;
        temp += value2;
        return temp;
    }
    

    EDIT: 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?

  • 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...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜