【发布时间】:2013-02-02 19:18:59
【问题描述】:
可能重复:
Solution for overloaded operator constraint in .NET generics
Implementing arithmetic in 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;
}
}
在方法 TestLine2(ref T a, ref T b, ref T c) 里面我遇到了以下问题:
Operator '+' cannot be applied to operands of type 'T' and 'T'
【问题讨论】:
-
这是 C# 中相当常见的问题。您不能在 T 上定义约束来指定“T 必须实现 + 运算符”
-
你还没有将
T限制为+able类型,所以编译器无法知道+可以应用于T。 -
大约 10,000 个早期问题的重复:stackoverflow.com/search?q=%5Bc%23%5D+%5Bgenerics%5D+arithmetic 寻找 Marc Gravell 写的答案,他很好地解决了这个问题