简体   繁体   English

无法将类型隐式转换为类型参数 - C# generics

[英]Cannot implicitly convert type to type parameter - C# generics

I have declared a method with input and output type parameters.我已经声明了一个带有输入和 output 类型参数的方法。 I have put some constrainsts on these types.我对这些类型设置了一些限制。 See code below.请参阅下面的代码。

class Input { public int I { get; set; } }
    class InputType1 : Input { }
    class InputType2 : Input { }

    class Output { public int O { get; set; } }
    class OutputType1 : Output { }

    static TOutput Method<TInput, TOutput>(TInput input) 
        where TInput : Input 
        where TOutput : Output
    {
        var output = new Output() { O = input.I * 2 };
        return output; //  compile error: connot do conversion implicitly
    }

Why does the conversion can be done implicitly on the variable 'input' and not on the variable 'output'?为什么转换可以在变量“输入”而不是在变量“输出”上进行隐式转换?

The compiler cannot infer out the concrete type of Output .编译器无法推断出Output的具体类型。 The only thing the compiler knows the return type is some type that inherits from Output .编译器唯一知道返回类型的是从Output继承的某种类型。

To create an instance of TOuptut change your code to要创建TOuptut的实例,请将您的代码更改为

static TOutput Method<TInput, TOutput>(TInput input) 
        where TInput : Input 
        where TOutput : Output, new()
    {
        var output = new TOutput() { O = input.I * 2 };
        return output;
    }

Note the new() constraint requires that a parameterless constructor must exist on TOutput .请注意new()约束要求TOutput上必须存在无参数构造函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM