简体   繁体   English

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

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

Can anyone explain why I have to cast to T and why Add2 does not accept Bar as a parameter? 谁能解释为什么我必须转换为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);
}

It may not be appropriate. 这可能不合适。 For example, consider: 例如,考虑:

class Other : Bar {}

...

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

With your current code, that would be calling do.Add2(new Bar()) ... which is clearly invalid as a Bar isn't an Other , required by IDo<Other>.Stuff . 根据您当前的代码,将被调用do.Add2(new Bar()) ...这显然是无效的,因为一Bar是不是Other ,所要求的IDo<Other>.Stuff

Casting to T (or using as ) isn't appropriate either - you can't cast a new Bar() to Other , and if you use as you'll just get a null reference. 强制转换为T (或使用as )也不合适-您不能将new Bar()Other ,并且如果使用as只会得到一个空引用。

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

相关问题 为什么我不能将&#39;as&#39;用于限制为接口的泛型类型参数? - Why can't I use 'as' with generic type parameter that is constrained to be an interface? 为什么不能将一个受约束的开放泛型类型转换为受约束类型? - Why can't you cast a constrained open generic typed to the constrained type? 如何使用带有强制转换的泛型参数(限制为整数类型)实现方法? - How can I implement a method with a generic parameter (constrained to an integer type) with a cast? 为什么不能将`this`转换为泛型? - Why can't I cast `this` to a generic type? 为什么必须使用动态输入参数来强制转换强类型函数? - Why do I have to type-cast a strongly typed function using a dynamic input-parameter? 为什么我不能将泛型类型转换为值类型 - Why can't I cast a generic type to a value type 为什么我不能将对象强制转换为约束泛型? - Why can't I cast an object to a constrained generic? 为什么不能将通用类型转换为继承类型? - Why can't I cast generic type to inheriting type? 为什么我不能将泛型类型的一个实例化转换为另一个? - Why can't I cast one instantiation of a generic type to another? 无法使用类型参数将派生类型强制转换为基类抽象类 - Can't cast derived type to base abstract class with type parameter
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM