簡體   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