泛型運算相關
如何運用 泛型 來達到判斷藉由輸入的型態 (T隨著型態改變)在進而做運算呢?
例 int x=3;
int y=2;
total=5;
string x="123";
string y="456";
toral="123456";
謝謝您不吝嗇的指教。 --------------------编程问答--------------------
public static T Sum<T>(T X, T Y)
{
var total=new object();
if (X is int && Y is int)
{
int x =Convert.ToInt32(X);
int y = Convert.ToInt32(Y);
total = x + y;
}
if (X is string && Y is string)
{
string x = X.ToString();
string y = Y.ToString();
total = x + y;
}
return (T)total;
}
int total= Sum<int>(1,2); //3
string total1 = Sum<string>("1", "2"); //"12"
算术运算符不能直接作用于泛型
这样满足你的需求不?
--------------------编程问答-------------------- 如果你的泛型参数是那些C#的基础类型的话,那就直接加好了,不用判断,因为这些类型都已经重载操作符+了 --------------------编程问答-------------------- 有人可以教學一下泛型嗎? --------------------编程问答-------------------- 不用泛型,可以使用表达式树。
然后再编译执行。 --------------------编程问答-------------------- 路过! --------------------编程问答-------------------- 帮你顶顶先
补充:.NET技术 , C#