2009-08-28 150 views
40

我在這個上畫了一個空白,看起來似乎找不到以前編寫的任何示例。我試圖實現一個類的通用接口。當我實現接口時,我認爲有些東西不能正常工作,因爲Visual Studio會不斷產生錯誤,說我沒有實現通用接口中的所有方法。使用通用方法實現接口

這裏是我工作的一個存根:

public interface IOurTemplate<T, U> 
{ 
    IEnumerable<T> List<T>() where T : class; 
    T Get<T, U>(U id) 
     where T : class 
     where U : class; 
} 

那麼應該怎麼我的課是什麼樣子?

+1

錯誤的問題標題。在普通的類和接口中有通用的方法,並且有方法的通用接口。 – Kobor42 2014-03-14 06:13:58

回答

69

你應該返工你的界面,就像這樣:

public interface IOurTemplate<T, U> 
     where T : class 
     where U : class 
{ 
    IEnumerable<T> List(); 
    T Get(U id); 
} 

然後,你可以實現它作爲一個泛型類:

public class OurClass<T,U> : IOurTemplate<T,U> 
     where T : class 
     where U : class 
{ 
    IEnumerable<T> List() 
    { 
     yield return default(T); // put implementation here 
    } 

    T Get(U id) 
    { 

     return default(T); // put implementation here 
    } 
} 

或者,你可以具體實現:

public class OurClass : IOurTemplate<string,MyClass> 
{ 
    IEnumerable<string> List() 
    { 
     yield return "Some String"; // put implementation here 
    } 

    string Get(MyClass id) 
    { 

     return id.Name; // put implementation here 
    } 
} 
+0

完美。我知道我必須指定通用變量,但不記得在哪裏(沒有雙關語意圖)。謝謝里德! – 2009-08-28 03:34:48

+1

期望的結果可能不可能,但IMO此答案不具有通用方法,而是具有依賴方法的泛型類。從技術上講,通用方法似乎有自己的模板參數。 – Catskul 2013-07-18 21:12:40

+0

你說得對。錯誤的問題標題,但這個問題的答案很好。 – Kobor42 2014-03-14 06:12:23

9

我想你可能要重新定義你的界面是這樣的:

public interface IOurTemplate<T, U> 
    where T : class 
    where U : class 
{ 
    IEnumerable<T> List(); 
    T Get(U id); 
} 

我想你想的方法來使用(再利用),其中他們宣佈通用接口的通用參數;而且你可能不想用它們自己的(不同於接口的)泛型參數來生成泛型方法。

鑑於接口,因爲我重新定義它,你可以這樣定義一個類:

class Foo : IOurTemplate<Bar, Baz> 
{ 
    public IEnumerable<Bar> List() { ... etc... } 
    public Bar Get(Baz id) { ... etc... } 
} 

或定義一個通用類是這樣的:

class Foo<T, U> : IOurTemplate<T, U> 
    where T : class 
    where U : class 
{ 
    public IEnumerable<T> List() { ... etc... } 
    public T Get(U id) { ... etc... } 
} 
+0

您也可以將其實現爲一個通用類,即:class Foo :IOurTemplate - 我不確定Jason之後的選項。 – 2009-08-28 02:29:08

+0

你說得對,我會補充一點。 – ChrisW 2009-08-28 02:31:14

1

- 編輯

的其他答案更好,但是請注意,如果你對它的外觀感到困惑,你可以讓VS爲你實現接口。

下面描述的過程。

好時,Visual Studio告訴我,它應該是這樣的:

class X : IOurTemplate<string, string> 
{ 
    #region IOurTemplate<string,string> Members 

    IEnumerable<T> IOurTemplate<string, string>.List<T>() 
    { 
     throw new NotImplementedException(); 
    } 

    T IOurTemplate<string, string>.Get<T, U>(U id) 
    { 
     throw new NotImplementedException(); 
    } 

    #endregion 
} 

注意,我所做的就是寫界面,然後點擊它,然後等待的小圖標,彈出有VS生成實施我:)

+0

參見:儘管你在接口中專門設計了'T'和'U'(它們都是'string'),這些方法本身是通用的,它們有自己獨立/不同的泛型參數......這可能不是OP意。 – ChrisW 2009-08-28 02:26:00

+0

我同意,我認爲你的建議很好,我只是展示瞭如何讓VS爲你實現接口,如果你對它的外觀感到困惑的話。 – 2009-08-28 02:27:58