[英]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>
因為B
和C
實現了A1
DoSomething<D, E>()
因為D
和E
都實現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沒有實現。 這可能嗎?
(我認為我在那兒已在使用“父母”一詞,但希望它仍然很清楚)
您唯一可以做的就是提供第三個通用類型參數,該參數可讓您指定T
和U
必須實現的接口:
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.