C# Generic Method, cannot implicit convert

前端 未结 4 1387
旧时难觅i
旧时难觅i 2021-01-11 20:32

I\'ve got the following code:

public static T GetCar() where T : ICar
{
    T objCar = default(T);

    if (typeof(T) == typeof(SmallCar)) {
                


        
4条回答
  •  感动是毒
    2021-01-11 21:04

    Your code is illegal because while you might be testing and know that your given T is BigCar or some other such type, the compiler cannot know that in advance and therefore the code is illegal. Based upon your given usage, you could have

    public static T GetCar() where T : ICar, new()
    {
        return new T();
    }
    

    The new() constraint allows you to invoke the default (parameterless) constructor on a type.

提交回复
热议问题