我写了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)
由于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);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6941 次 |
| 最近记录: |