无法将类型隐式转换为类型参数-C#泛型
我声明了一个具有输入和输出类型参数的方法。我对这些类型设置了一些约束条件。请参阅下面的代码无法将类型隐式转换为类型参数-C#泛型,c#,generics,C#,Generics,我声明了一个具有输入和输出类型参数的方法。我对这些类型设置了一些约束条件。请参阅下面的代码 class Input { public int I { get; set; } } class InputType1 : Input { } class InputType2 : Input { } class Output { public int O { get; set; } } class OutputType1 : Output { } static
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
}
类输入{public int I{get;set;}
类InputType1:输入{}
类InputType2:输入{}
类输出{public int O{get;set;}}
类OutputType1:输出{}
静态TOutput方法(TInput输入)
其中TInput:Input
其中TOutput:Output
{
var output=new output(){O=input.I*2};
返回输出;//编译错误:隐式执行转换
}
为什么可以隐式地对变量“input”而不是对变量“output”进行转换?编译器无法推断出
输出的具体类型。编译器只知道返回类型是从Output
继承的某个类型
要创建TOuptut
的实例,请将代码更改为
static TOutput方法(TInput输入)
其中TInput:Input
其中TOutput:Output,new()
{
var output=new TOutput(){O=input.I*2};
返回输出;
}
注意new()
约束要求TOutput
上必须存在无参数构造函数并非每个输出都是TOutput
。这是行不通的,你想干什么?是否要返回输出
?或者要将TOutput
约束为new()
,以便调用newtoutput(){O=input.I*2}代码>?@Joelius我想返回类型输出或其任何派生。也许我会返回一个输出类型或TOutput。我明白为什么转换是不可能的。