DAY 5
3

## LINQ自學筆記-打地基-泛型方法

``````int Max(int a, int b)
{
if (a > b) return a;
else return b;
}

void Main()
{
int result = Max(4, 8);
result.Dump();
}

//輸出：8
``````

``````object Max(object a, object b)
{
if (a > b) return a;
else return b;
}

void Main()
{
int retInt = (int)Max(4, 8);
retInt.Dump();
float retFloat = (float)Max(4.5F, 8.9F);
retFloat.Dump();
}
``````

``````IComparable Max(IComparable a, IComparable b)
{
if (a.CompareTo( b) > 0) return a;
else return b;
}

void Main()
{
int retInt = (int)Max(4, 8);
retInt.Dump();  //輸出 8
float retFloat = (float)Max(4.5F, 8.9F);
retFloat.Dump();  //輸出8.9
}
``````

1. 若傳入兩個都有實做 IComparable 介面的型別，但是卻是不同型別，執行時期會發生 ArgumentException。

2. 每次使用這段程式，都必須進行型別轉換，頻繁的轉型會讓程式的效能低落。

``````T Max<T>(T a, T b) where T : IComparable<T>
{
if (a.CompareTo(b) > 0 ) return a;
else return b;
}
``````

int Max(int a, int b)

``````class Base { }
class Test<T, U>
where U : struct
where T : Base, new() { }
``````

``````void Main()
{
int retInt = Max<int>(4, 8);
retInt.Dump();  //輸出 8
float retFloat = Max<float>(4.5F, 8.9F);
retFloat.Dump();  //輸出8.9
object retObject = Max<string>("LEO", "FOO");
retObject.Dump(); //輸出 LEO
}
``````

``````T Max<T>(T a, T b) where T : IComparable<T>
{
if (a.CompareTo(b) > 0 ) return a;
else return b;
}

void Main()
{
var retInt = Max(4, 8);
retInt.Dump();  //輸出 8
var retFloat = Max(4.5F, 8.9F);
retFloat.Dump();  //輸出8.9
var retObject = Max("LEO", "FOO");
retObject.Dump(); //輸出 LEO
}
``````