无法传递符合通用约束的类型的变量 [英] Cannot pass variable of type conforming to generic constraint
问题描述
public interface ILovable<T> where T : IEquatable<T>
{
T Care(T t);
}
public class Me : ILovable<int>
{
public int Care(int i)
{
return i;
}
}
说我有以上。现在,以下功能失效:
Say I have the above. Now below function fails:
private static void Colour<T>(ILovable<T> me) where T : IEquatable<T>
{
var z = me.Care(1); //cannot convert from 'int' to 'T'
}
什么是失败的上述转换一段代码? ILovable< T>
有一个护理
函数进水口 T
这是 IEquatable< T>
。在上面的功能我打电话同护理
函数并传递 T
是 INT
键入。 INT
毕竟是 IEquatable< INT方式>
What's failing the above piece of code? ILovable<T>
has a Care
function which intakes a T
which is IEquatable<T>
. In the above function I'm calling the same Care
function and passing T
which is int
type. int
is after all IEquatable<int>
.
的我在做什么错了?是否有任何变通得到它固定的吗?的
推荐答案
简短的回答是压倒类型的变量 T
里面的一个泛型方法(或类)用更派生类型是不可能的,因为编译器不知道明确 T
是更多的派生类型(在我们的例子 T
是 INT
),因为 T $ C 。$ C>可在运行时其他任何派生类型
The short answer is overriding variable of type T
inside a generic method (or class) with a more derived type is not possible since compiler doesn't explicitly know T
is that more derived type (in our case T
is int
), because T
can be any other more derived type at run time.
龙回答:我
变量的类型的 ILovable< T>
。现在 me.Care
函数需要的是被指定类型的参数 ILovable< T>
是 T
。外护理
函数 T
可以是任何东西也就是 IEquatable< T>
,所以 INT
即可。但里面的功能, T
必须是公正 T
而不是其他派生类型的 IEquatable< ; T>
。否则会出现运行错误这样的情况:
Long answer: me
variable is of type ILovable<T>
. Now me.Care
function is expecting parameter of type that is specified on ILovable<T>
which is T
. Outside the Care
function T
can be anything that is IEquatable<T>
, so int
is ok. But inside the function, T
has to be just T
and not another derived type of IEquatable<T>
. Otherwise there will be runtime error for scenarios like this:
private static void Colour<T>(ILovable<T> me) where T : IEquatable<T>
{
var z = me.Care(1);
}
...
Colour("");
目前, T
是字符串时调用颜色()
。因此,我
是 ILovable<串GT;
。因此, me.Care
函数需要字符串
作为参数,但提供的是一种 INT
,这是一场灾难。
Right now, T
is string when calling Colour("")
. So me
is ILovable<string>
. So me.Care
function expects a string
as parameter but provided is an int
and that is disaster.
这篇关于无法传递符合通用约束的类型的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!