簡體   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