(一)泛型類

代碼
我的本意是要將一個實體參數轉換為泛型對象T返回,所以初次代碼就寫成下面這樣:
public static T GetObj<T>(Employee model)
{
T result = default(T);
if (model is T)
{
result = (T)model; //或者 result = model as T;
}
return result;
}
可是,編譯器提示無法將類型轉換為T,之前竟然沒碰到過這個問題。查了一下資料,原來,要這么寫:
public class GenericTest
{
//public static T GetObj<T>(Employee model)
//{
// T result = default(T);
// if (model is T)
// {
// result = (T)model; //或者 result = model as T;
// }
// return result;
//}
public static T GetObj<T>(Employee model)
{
T result = default(T);
if (model is T)
{
result = (T)(object)model; //或 (T)((object)model);
}
return result;
}
}
天殺的ms。