簡體   English   中英

如何在 C# 中編寫泛型方法

[英]How to write generic way method in C#

我有個人方法,例如:

 public string Method1()
   {
      class1 c1= new class1 ();
      var data = c1.GetMainData(Id);
      var value= c1.GetValue(data,c1);
   }

  public string Method2()
    {
       class2 c2= new class2 ();
       var data = c2.GetMainData(Id);
       var value= c2.GetValue(data,c2);
    }

  public string Method3()
    {
       class3 c3 = new class3 ();
       var data = c3.GetMainData(Id);
       var value= c3.GetValue(data,c3);
    }
                   

從上面的函數來看,類class1class2class3不同,但類中的方法名稱GetMainDataGetValue相同。

  • 方法名稱相同,並將類對象傳遞給方法,並具有不同的功能和返回字符串。

請幫我寫一個通用的單一方法來處理?

您是否嘗試過編寫通用方法?

interface IMyInterface
{
    string GetMainData(string id);
    string GetValue(string data);
}

string getValue<T>() where T:IMyInterface,new()
{
    var c = new T();
    var data = c.GetMainData(Id);
    return c.GetValue(data);
}

where子句表示T的最低要求,在這種情況下,作為 T 傳遞的任何類都必須從IMyInterface繼承並具有空構造函數,因此編譯器知道T必須具有new()以及在IMyInterface接口

附加說明:如果您使用的是接口,那么甚至可能不需要泛型,因為您可以在不知道它們是什么類的情況下調用實例函數

string getValue(IMyInterface c)
{
    var data = c.GetMainData(Id);
    return c.GetValue(data);
}

通常僅當您需要返回或輸入與 T 類型相同時才需要泛型

我寫的最常見的泛型是集合擴展

public static Add(this ICollection<T> col, IEnumerable<T> items)
{
   foreach(var item in items)
       col.Add(item)
}

在這里,如果項目與集合的類型不同,則代碼不起作用,但是我們實際上並不關心項目和集合的類型,只要它們匹配即可

與 C++ 不同,C# 只有有限的鴨子類型,並且僅用於編譯器內部(處置)或擴展方法。 它們都不適用於這里。

您在這里有三個選擇。 您可以使用通用的多態基類型來調用您的方法:

interface I { 
    object GetMainData(int id);
    object GetValue(int data);
}

class class1 : I {
    // implement the interface
}

// same for class2 and class3

public string Method<T>() where T: I, new()
{
     var c = new T();
     var data = c.GetMainData(Id);
     var value= c.GetValue(data);
     // return something
}

您還可以使用反射從不相關的對象中按名稱調用方法。

當然,您可以使用dynamic創建一個編譯器站點來為您做同樣的事情。

請注意,最后兩個選項比第一個選項慢幾個數量級,盡管dynamic的成本主要是在第一次調用構建站點和編譯新生成的代碼時,后續調用非常快。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM