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

int*_*ork -1 c# generics

可能重复:
.NET泛型中重载运算符约束的解决方案在泛型中
实现算术运算?

我写了Generics类,但我遇到了标题中描述的问题.

class Program
    {
        static void Main(string[] args)
        {
            int a = 1;
            int b = 2;
            int c = 3;

            dynamic obj = new Gen<int>();
            obj.TestLine1(ref a, ref b);
            obj = new Gen<string>();
            obj.TestLine2(ref a, ref b, ref c);
            System.Console.WriteLine(a + " " + b);
            Console.ReadLine();
        }
    }

public class Gen<T>
    {
        public void TestLine1(ref T a, ref T b)
        {
            T temp;
            temp = a;
            a = b;
            b = temp;
        }
        public void TestLine2(ref T a, ref T b, ref T c)
        {
            T temp;
            temp = a;
            a = a + b;
            b = a + c;
            c = a + b;
        }
    }
Run Code Online (Sandbox Code Playgroud)

在方法TestLine2内部(ref T a,ref T b,ref T c)我遇到问题:

Operator '+' cannot be applied to operands of type 'T' and 'T'
Run Code Online (Sandbox Code Playgroud)

Lee*_*Lee 6

由于T可以是任何类型,因此无法保证T具有静态+运算符.在C#中有没有办法约束T,以支持静态运营商一样+,所以你必须要通过函数使用的值组合TTestLine2:

public void TestLine2(ref T a, ref T b, ref T c, Func<T, T, T> op)
{
    T temp;
    temp = a;
    a = op(a, b);
    b = op(a, c);
    c = op(a, b);
}
Run Code Online (Sandbox Code Playgroud)