c#中的自定義泛型類、泛型方法和泛型接口


​    泛型的產生其中一個原因就是為了解決原來集合類中元素的裝箱和拆箱問題:

一、泛型類:

    /// <summary>
    /// 返回前台的消息
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class YZT_Message<T>
    {
        private int m_Request_Type = 1;

        // 返回前台的成功錯誤類型:1:成功(默認)   0:錯誤
        public int Request_Type
        {
            get { return m_Request_Type; }
            set { m_Request_Type = value; }
        }

        private string m_Request_Message = "當前錯誤";

        //返回前台的信息 Request_Type == 0 時,才會取當前錯誤數據
        public string Request_Message
        {
            get { return m_Request_Message; }
            set { m_Request_Message = value; }
        }

        // 回返前台的信息,可能是JSON對象
        public T Request_Object { get; set; }

        // 回返前台的信息,可能是JSON對象集合
        public IList<T> Request_List { get; set; }
    }

調用的時候:假如T是string類型:

    YZT_Message<string> pMessage = new YZT_Message<string>();

    try{

        pMessage.Request_Object = "OK";

        pMessage.Request_Type = 1;

    }

   catch (Exception err){

        pMessage.Request_Type = 0;

        pMessage.Request_Message = err.Message;

    }

二、泛型方法:

public class Demo
    {
        //這是一個泛型方法,可以在普通類中
        public static void Swap<T>(ref T lhs, ref T rhs)
        {
            T temp;
            temp = lhs;
            lhs = rhs;
            rhs = temp;
        }

        //調用泛型方法:
        public static void TestSwap()
        {
            int a = 1;
            int b = 2;
            Swap<int>(ref a, ref b);//也可以省略類型參數,編譯器將推斷出該參數。Swap(ref a, ref b);
            System.Console.WriteLine(a + " " + b);
        }
    }

三、泛型接口

public class Demo
    {
        public interface IFace<T>
        {
            T SayHi();
            void SayHello(T msg);
        }
    }

實現泛型接口:

方式一:普通類實現泛型接口:

public class InterFaceDemo2 : WebApplication1.InterFaceDemo.IFace<string> 
    {

        public string SayHi()
        {
            throw new NotImplementedException();
        }

        public void SayHello(string msg)
        {
            throw new NotImplementedException();
        }
    }

方式二:泛型類,實現泛型接口,這樣更靈活

public class InterFaceDemo<T>:WebApplication1.InterFaceDemo.IFace<T>
    {

        public T SayHi()
        {
            throw new NotImplementedException();
        }

        public void SayHello(T msg)
        {
            throw new NotImplementedException();
        }
    }

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM