C# 为什么我必须强制转换为类型参数,而不能使用受约束的类型?
有人能解释为什么我必须转换为T,为什么Add2不接受Bar作为参数吗C# 为什么我必须强制转换为类型参数,而不能使用受约束的类型?,c#,generics,casting,generic-variance,C#,Generics,Casting,Generic Variance,有人能解释为什么我必须转换为T,为什么Add2不接受Bar作为参数吗 class Foo<T> where T : class, IBar { void Add1(IDo<T> @do) { @do.Stuff(new Bar() as T); } // Add2 does not compile: // Argument type Bar is not assignable to parameter Type T void Add2(I
class Foo<T> where T : class, IBar
{
void Add1(IDo<T> @do) { @do.Stuff(new Bar() as T); }
// Add2 does not compile:
// Argument type Bar is not assignable to parameter Type T
void Add2(IDo<T> @do) { @do.Stuff(new Bar()); }
}
interface IBar {}
class Bar : IBar {}
interface IDo<in T> {
void Stuff(T bar);
}
这可能不合适。例如,考虑:
class Other : Bar {}
...
IDo<Other> do = new DoImpl<Other>();
Foo<Other> foo = new Foo<Other>();
foo.Add2(do);
使用当前代码,将调用do.Add2new Bar。。。这显然是无效的,因为一个酒吧不是IDo.Stuff所要求的其他酒吧
强制转换为T或使用as也不合适-您不能将新条强制转换为其他条,如果使用as,您将得到一个空引用。这可能不合适。例如,考虑:
class Other : Bar {}
...
IDo<Other> do = new DoImpl<Other>();
Foo<Other> foo = new Foo<Other>();
foo.Add2(do);
使用当前代码,将调用do.Add2new Bar。。。这显然是无效的,因为一个酒吧不是IDo.Stuff所要求的其他酒吧
强制转换为T或使用as也不合适-您不能将新条强制转换为其他条,如果使用as,您将只获得一个空引用。Add2不接受IBar或其子类之一。您必须给它一个IDo参数。@mrt181:是的,对不起-上次调用的是foo.Add2do;。现在已修复-希望这能说明问题所在。Add2不接受IBar或其子类之一。您必须给它一个IDo参数。@mrt181:是的,对不起-上次调用的是foo.Add2do;。现在已修复-希望这能说明问题所在。