C#Generic Method,不能隐式转换

MeT*_*tus 8 c# generics methods

我有以下代码:

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;
}
Run Code Online (Sandbox Code Playgroud)

这是我得到的错误: Cannot implicitly convert type 'Test.Cars' to 'T'

我在这里失踪了什么?所有车型均采用ICar接口.

谢谢

Fel*_* K. 9

您无法转换为T因为在编译时不知道T这一事实.如果要使代码生效,可以将返回类型更改为ICar并删除泛型T返回类型.

你也可以演员T.这也会奏效.如果您只使用默认构造函数,那么您也可以new()使用它new T()来使用以使代码工作.

样品

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;
}
Run Code Online (Sandbox Code Playgroud)

投:

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;
}
Run Code Online (Sandbox Code Playgroud)

新的约束:

public T GetCar<T>()
    where T : ICar, new()
{
    return new T();
}
Run Code Online (Sandbox Code Playgroud)


Ant*_*ram 7

您的代码是非法的,因为虽然您可能正在测试并知道您的给定T是BigCar或其他类型的,但编译器无法提前知道,因此代码是非法的.根据您的用途,您可以拥有

public static T GetCar<T>() where T : ICar, new()
{
    return new T();
}
Run Code Online (Sandbox Code Playgroud)

new()约束可以让你调用一个类型的默认(无参数)构造函数.