C#中的各種泛型

來源:互聯網
上載者:User

標籤:c#中的各種泛型

上一篇文章簡單瞭解了一下強型別以及泛型的知識。其實,在.net類庫中有很多的泛型定義,最典型也是我們用的最多的就是List<>和Dictionary<Tkey,Tvalue>兩個泛型集合。這隻是微軟我們提供的,在實際開發中,我們很多時候還需要自己定義一些泛型,今天就接著上次的內容來具體學習一下泛型的各種定義。

一、泛型類

1.定義

    //泛型類,泛型的好處,還是代碼重用。    // where yzk : struct泛型約束    //where T : struct表示只能是實值型別    public class MyClass<yzk, sk, jk, nrg, yhb>        where yzk : struct //限定yzk只能是實值型別        where sk : class, IComparable //限定sk只能是參考型別        where jk : ICollection, new()   //表示jk必須是實現了ICollection介面的類型        where yhb : nrg    {        public yzk[] _data;        public sk _ss;        public jk _jj;        public MyClass(params yzk[] objs)        {            this._data = objs;        }        public void SayHi(yzk msg)        {            Console.WriteLine(msg);        }        public void Show()        {            foreach (var item in _data)            {                Console.WriteLine(item);            }        }    }
2.泛型類的執行個體化
        static void Main(string[] args)        {            MyClass<string> mc = new MyClass<string>("aaa", "bbbb", "ccc");            mc.SayHi("大家好。");            MyClass<int> mcc = new MyClass<int>(1, 2, 3, 4);            mcc.Show();            Console.ReadKey();        }

二、泛型介面

1.定義

    public interface IFlyable<T>    {        void Fly(T msg);    }
2.介面的繼承

類實現介面的時候有兩種情況:該類是普通的類、該類也是泛型類

普通類

    public class MyClass : IFlyable<string>    {        #region IFlyable<string> 成員        public void Fly(string msg)        {            throw new NotImplementedException();        }        #endregion    }    public class MyClass1 : IFlyable<int>    {        #region IFlyable<int> 成員        public void Fly(int msg)        {            throw new NotImplementedException();        }        #endregion    }

泛型類

    public class MyClass2<yzk> : IFlyable<yzk>    {        #region IFlyable<T> 成員        public void Fly(yzk msg)        {            throw new NotImplementedException();        }        #endregion    }

三、泛型方法

        public void SayHi<T>(T msg)        {            Console.WriteLine(msg);        }

注意:對於泛型方法,調用的時候,可以指定泛型,也可以不指定泛型,可以自動推斷。

            //mc.SayHi<int>(100);            // mc.SayHi<string>("aaaaaaaaaaaaaaaa");            //mc.SayHi(1000);

四、泛型委派

public delegate void Notice<T>(T name);

C#中的各種泛型

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.