c#泛型作为返回类型的写法
没有技术含量,已经知道的就直接无视了吧。
我的本意是要将一个实体参数转换为泛型对象T返回,所以初次代码就写成下面这样:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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 result = default(T);
if (model is T)
{
result = (T)model; //或者 result = model as T;
}
return result;
}
可是,编译器提示无法将类型转换为T,之前竟然没碰到过这个问题。查了一下资料,原来,要这么写:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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;
}
}
{
//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。
作者:Jeff Wong
出处:http://jeffwongishandsome.cnblogs.com/
本文版权归作者和博客园共有,欢迎围观转载。转载时请您务必在文章明显位置给出原文链接,谢谢您的合作。