集合和泛型12—–泛型代碼中的預設關鍵字

來源:互聯網
上載者:User

 

在編寫泛型類或者泛型方法的時候,有時候可能需要將型別參數T的預設值賦值給一個型別參數T的一個變數。可是,在泛型沒有具體執行個體化以前,T到底代表的資料類型是什麼,這個不得而知。T到底是實值型別還是參考型別?如果T為實值型別,則它是數值還是結構?

給定參數化型別T的一個變數t,只有當T為參考型別時,語句t = null才有效;只有當 T 為數實值型別而不是結構時,語句 t = 0才能正常使用。

解決方案是使用default關鍵字,此關鍵字對於參考型別會返回空,對於數實值型別會返回零。對於結構,此關鍵字將返回初始化為零或空的每個結構成員,具體取決於這些結構是實值型別還是參考型別。

例子DefaultValue使用default關鍵字測試了一些類型的預設值。

namespace DefaultValue

{

    class Point

    {

    }

    struct Student

    {

    }

 

    class Program

    {

        static void Main(string[] args)

        {

            Console.WriteLine(default(int));

            Console.WriteLine(default(double));

            Console.WriteLine(default(string));

            Console.WriteLine(default(Point));

            Console.WriteLine(default(Student));

            Console.ReadKey();

        }

    }

}

程式啟動並執行結果是

下面的代碼示範了default使用

public class GenericList<T>

{

    private class Node

    {

        //...

        public Node Next;

        public T Data;

    }

    private Node head;

    //...

    public T GetNext()

    {

        T temp = default(T);

        Node current = head;

        if (current != null)

        {

            temp = current.Data;

            current = current.Next;

        }

        return temp;

    }

}

 

聯繫我們

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