代码之家  ›  专栏  ›  技术社区  ›  Jason N. Gaylord

使用泛型方法实现接口

  •  45
  • Jason N. Gaylord  · 技术社区  · 15 年前

    我在这张图上画了一个空白,似乎找不到我以前写过的任何例子。我正在尝试用一个类实现一个通用接口。当我实现接口时,我认为有些东西不起作用,因为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;
    }
    

    我的课应该是什么样子?

    3 回复  |  直到 15 年前
        1
  •  85
  •   Reed Copsey    15 年前

    您应该重新编写接口,如下所示:

    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
        }
    }
    
        2
  •  10
  •   ChrisW    15 年前

    我认为您可能希望像这样重新定义接口:

    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... }
    }
    
        3
  •  1
  •   Noon Silk    15 年前

    --编辑

    其他的答案更好,但请注意,如果您对界面的外观感到困惑,您可以让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为我生成实现:)