2017-09-05 132 views
0

假設我有一個接口IA,其中包含一個名爲Foo的泛型方法。C# - 匹配派生類型的接口通用方法約束

public interface IA { 
    int Foo<T>(T otherType); 
} 

我想噸至是同一類型的派生類:

class A : IA { 
    int Foo(A otherType) 
    { 
    } 
} 

我嘗試以下(語法錯誤):

public interface IA { 
    int Foo<T>(T otherType) where T : this; 
} 

如何我約束需要看起來像實現這一目標?

+0

不要以爲這是可能的。界面不知道將實施它。這基本上是雞/蛋的東西。 – Jamiec

回答

7

你將不得不做這樣的:

public interface IA<T> 
{ 
    int Foo(T otherType); 
} 

class A : IA<A> 
{ 
    public int Foo(A otherType) 
    { 
     return 42; 
    } 
} 

這是強制執行接口成員的泛型類型的唯一途徑。