1

谁能解释为什么我必须转换为 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(IDo<T> @do) { @do.Stuff(new Bar()); } 
}

interface IBar {}

class Bar : IBar {}

interface IDo<in T> {
    void Stuff(T bar);
}
4

1 回答 1

6

这可能不合适。例如,考虑:

class Other : Bar {}

...

IDo<Other> do = new DoImpl<Other>();
Foo<Other> foo = new Foo<Other>();
foo.Add2(do);

使用您当前的代码,这将调用do.Add2(new Bar())... 这显然是无效的,因为 a Baris not an Other,需要IDo<Other>.Stuff.

投射到T(或使用as)也不合适——你不能投射new Bar()Other,如果你使用as,你只会得到一个空引用。

于 2014-04-25T11:47:26.527 回答