繁体   English   中英

为什么我必须强制转换为类型参数,而不能使用受约束的类型?

[英]Why do I have to cast to type parameter and can't use the constrained type?

谁能解释为什么我必须转换为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);
}

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

class Other : Bar {}

...

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

根据您当前的代码,将被调用do.Add2(new Bar()) ...这显然是无效的,因为一Bar是不是Other ,所要求的IDo<Other>.Stuff

强制转换为T (或使用as )也不合适-您不能将new Bar()Other ,并且如果使用as只会得到一个空引用。

暂无
暂无

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

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