2009-08-28 148 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