繁体   English   中英

使用通用方法实现接口

[英]Implement an Interface with Generic Methods

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

那我班上应该怎么样?

您应该重新设计界面,如下所示:

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
    }
}

我想你可能想重新定义你的界面,如下所示:

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... }
}

- 编辑

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM