C# 泛型运算符'+';无法应用于类型为';T';和';T';
可能重复:C# 泛型运算符'+';无法应用于类型为';T';和';T';,c#,generics,C#,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,
我编写了泛型类,但我遇到了标题中描述的问题
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;
}
}
因为T的类型在实例化之前是未知的,所以不能保证类型T将支持+运算符 由于
T
可以是任何类型,因此不能保证T
将具有静态+
运算符。在C#中,无法约束T
以支持像+
这样的静态运算符,因此必须将用于组合T
值的函数传递到TestLine2
:
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);
}
public void TestLine2(参考T a、参考T b、参考T c、功能操作)
{
温度;
温度=a;
a=op(a,b);
b=op(a,c);
c=op(a,b);
}
假设我创建了一个类的实例,如下所示:var gen=new gen()
。现在T
意味着Object
在类的这个实例中无处不在。当您调用TestLine2()
时,该方法将尝试添加到对象中,这是在C#中无法完成的
更广泛地说,由于C#在创建Gen
对象之前不知道要使用什么类型的参数,因此它限制您仅使用为所有对象定义的方法
在我看来,您真的希望
TestLine2
成为一种组成字符串的方法。为什么不把Gen
变成一个非泛型类,让它在任何地方都使用String
s呢?你不知道t
是否实现了+运算符。如果将object
作为类型参数传递会怎么样?这是C#中非常常见的问题。你不能在t上定义一个约束来指定“t必须实现+运算符”。你没有将t
限制为+
可执行类型,因此编译器无法知道+
可以应用于t
。重复之前的大约10000个问题:寻找Marc Gravell写的答案,他很好地解决了这个问题,这是事实,但这只是一个诊断,而不是一个解决办法。@Wicktor:没有问题,也没有研究努力。也许这就是OP想要的解释。
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);
}