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