C# 泛型


(一)泛型類

image

代碼

 

我的本意是要將一個實體參數轉換為泛型對象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。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM