C#泛型經典樣本

來源:互聯網
上載者:User
函數的參數不同叫多態,函數的參數類型可以不確定嗎?
函數的傳回值只能是一個嗎?函數的傳回值可以不確定嗎?
泛型是一種特殊的類型,它把指定類型的工作延遲到用戶端代碼聲明並執行個體化類或方法的時候進行。
下面是兩個經典樣本:1.輸入一個字串,轉化為想要的類型。利用泛型的特性,傳回值可以是指定的類型。2.比較兩個對象,傳回值較大的一個。using System;
using System.Collections.Generic;
using System.Text;

namespace FamilyManage
{
    class CGeneric
    {
        //資料轉換
        static public T Convert<T>(string s) where T : IConvertible
        {
            return (T)System.Convert.ChangeType(s, typeof(T));
        }
        //取兩個數較大的一個
        static public T Max<T>(T first, T second) where T : IComparable<T>
        {
            if (first.CompareTo(second) > 0)
                return first;

            return second;
        }
        //使用
        static public void test()
        {
            //
            int iMax = Max(123, 456);
            double dMax = Max<double>(1.23, 4.56);//可以指定傳回型別
            //
            int iConvert = Convert<int>("123456");
            float fConvert = Convert<float>("123.456");
            //
            System.Windows.Forms.MessageBox.Show(iMax + "|" + dMax + "|" + iConvert + "|" + fConvert);
        }
    }
}

from:http://www.it100.info/csharp-generic.html

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.