2022-09-07|閱讀時間 ‧ 約 6 分鐘

玩轉C#之【泛型】

介紹

在C#2.0時代以前,是沒有泛型的,所以當我們遇到需求是方法內做相同的事情,但因為輸入或輸出的型別不一樣,我們就必須重複寫出類似的程式
以下的例子是=不同的輸入型別 但卻做相同的事情 =印出輸入資料
範例:
  • 輸入參數:int或string或DateTime
  • 功能:印出輸入的"數值"
最直覺、簡單的做法會寫出三個方法
public class CommonMethod
   {
       /// <summary>
       /// 印出int數值
       /// </summary>
       /// <param name="iParameter"></param>
       public static void ShowInt(int iParameter)
       {
           Console.WriteLine("This is {0},parameter={1},type={2}",
               typeof(CommonMethod).Name, iParameter.GetType().Name, iParameter);
       }
       /// <summary>
       /// 印出string數值
       /// </summary>
       /// <param name="iParameter"></param>
       public static void ShowString(string iParameter)
       {
           Console.WriteLine("This is {0},parameter={1},type={2}",
               typeof(CommonMethod).Name, iParameter.GetType().Name, iParameter);
       }
       /// <summary>
       /// 印出DateTime數值
       /// </summary>
       /// <param name="iParameter"></param>
       public static void ShowDateTime(DateTime iParameter)
       {
           Console.WriteLine("This is {0},parameter={1},type={2}",
               typeof(CommonMethod).Name, iParameter.GetType().Name, iParameter);
       }
   }
主程式:
static void Main(string[] args)
       {
           int iValue = 123;
           string sValue = "123";
           DateTime dtValue = DateTime.Now;
           CommonMethod.ShowInt(iValue);
           CommonMethod.ShowString(sValue);
           CommonMethod.ShowDateTime(dtValue);
       }

如何定義和使用泛型

泛型: 2.0出現的新語法,解決了用一個方法,滿足不同參數型別,做相同的事
它將函式或方法,定義要使用的型別延緩到了,當你開始使用它才定義
泛型的基本結構是在function或class旁邊加上 的符號
裡面的 T= 只是一個名稱,也可以取其他名字如下
範例:
public class GenericMethod 
{
public static void Show<myName>(myName tParameter)
{
Console.WriteLine("This is {0},parameter={1},type={2}",
typeof(GenericMethod),tParameter.GetType().Name,tParameter.ToString());
}
}
主程式:
void Main()
{
try
{
int iValue = 123;
string sValue = "456";
DateTime dtValue = DateTime.Now;
GenericMethod.Show<int>(iValue);
GenericMethod.Show<string>(sValue);
GenericMethod.Show<DateTime>(dtValue);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
重點提醒
  • 2.0時代推出的
  • 把參數型別的定義延遲到使用的時候
  • 不是語法糖,而是2.0由框架升級堤供的功能
  • TypeName命名:不要用關鍵字 也不要跟類型衝突
關於泛型的好處與原理、泛型約束、泛型快取、協變、逆變之後會專門寫一篇文章跟大家講解

參考資料

本篇已同步發表至個人部落格 https://moushih.com/2022ithome07/
我的鐵人賽文章
https://ithelp.ithome.com.tw/articles/10288370
分享至
成為作者繼續創作的動力吧!
程式語言、理財自我投資、加密貨幣、資訊安全 https://moushih.com/
從 Google News 追蹤更多 vocus 的最新精選內容從 Google News 追蹤更多 vocus 的最新精選內容

發表回應

成為會員 後即可發表留言