簡體   English   中英

多個類型參數-約束到相同的基類?

[英]Multiple type parameters - constrain to same base class?

假設我們有這樣的類結構:

interface A { }
interface A1 : A { }
interface A2 : A { }
class B : A1 { }
class C : A1 { }
class D : A2 { }
class E : A2 { }

我想用此標頭聲明一個方法:

public void DoSomething<T, U>()
    where T : A
    where U : A
    <and also where U inherits/implements same parent as T>

它需要允許DoSomething<B, C>()

  • where T : A滿足B實現A
  • where U : A滿足C實現A
  • <and also where U inherits/implements same parent as T>因為BC實現了A1
  • 也允許DoSomething<D, E>()因為DE都實現A2

但是它不需要允許DoSomething<B, D>()

  • where T : A滿足B實現A
  • where U : A滿足C實現A
  • <and also where U inherits/implements same thing as T> 不能滿足,因為B實現了A1而D沒有實現。

這可能嗎?

(我認為我在那兒已在使用“父母”一詞,但希望它仍然很清楚)

您唯一可以做的就是提供第三個通用類型參數,該參數可讓您指定TU必須實現的接口:

public void DoSomething<T, U, V>()
    where T : V
    where U : V
    where V : A

現在,您可以執行DoSomething<D, E, A1>()但不能執行DoSomething<B, D, A1>()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM