本文介绍了C#通用方法,无法隐式转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下代码:
public static T GetCar<T>() where T : ICar
{
T objCar = default(T);
if (typeof(T) == typeof(SmallCar)) {
objCar = new SmallCar("");
} else if (typeof(T) == typeof(MediumCar)) {
objCar = new MediumCar("");
} else if (typeof(T) == typeof(BigCar)) {
objCar = new BigCar("");
}
return objCar;
}
这是我得到的错误:Cannot implicitly convert type 'Test.Cars' to 'T'
我在这里想念什么?所有类型的汽车都实现ICar接口.
What Am I missing here? All car types implement the ICar interface.
谢谢
推荐答案
由于T在编译时未知,因此您无法转换为T
.如果要使代码正常工作,可以将返回类型更改为ICar
并删除通用的T
返回类型.
You cannot convert to T
because of the fact that T isn't known at compile time.If you want to get your code to work you can change the return type to ICar
and remove the generic T
return type.
您还可以强制转换为T
.这也可以.如果仅使用默认构造函数,则还可以包含new()
并使用new T()
来使代码正常工作.
You also can cast to T
. This would work too.If you only using the default constructor you can also constain on new()
and use new T()
to get your code to work.
public ICar GetCar<T>()
where T : ICar
{
ICar objCar = null;
if (typeof(T) == typeof(SmallCar)) {
objCar = new SmallCar();
} else if (typeof(T) == typeof(MediumCar)) {
objCar = new MediumCar();
} else if (typeof(T) == typeof(BigCar)) {
objCar = new BigCar();
}
return objCar;
}
发布:
public T GetCar<T>()
where T : ICar
{
Object objCar = null;
if (typeof(T) == typeof(SmallCar)) {
objCar = new SmallCar();
} else if (typeof(T) == typeof(MediumCar)) {
objCar = new MediumCar();
} else if (typeof(T) == typeof(BigCar)) {
objCar = new BigCar();
}
return (T)objCar;
}
新约束:
public T GetCar<T>()
where T : ICar, new()
{
return new T();
}
这篇关于C#通用方法,无法隐式转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!