• ASP.Net
  • 常用語法介紹
  • 資料型別
  • import_contacts C# 自訂型別
    5748
適用範圍

學習程式設計的初階必學項目:宣告自定義的型別與使用方式

實用性:
重要性:

自訂型別可使用struct、class、interface 及 enum 來建構

除了原生型別 (例如 int, bool, string ...等等),能夠用來描述資料的結構則稱為自訂型別。

使用Struct來建立型別

類型是實值類型,通常可用來封裝一小組相關變數(例如座標)而且不得為NULL,它也不具備繼承的能力。
public struct myPosition
{
    public int x, y;

    public myPosition(int p1, int p2)
    {
        x = p1;
        y = p2;
    }
}
調用方式如下:
protected void Page_Load(object sender, EventArgs e)
{
   myPosition p = new myPosition(122,154);
}

使用Class來建立型別

通常我們稱class為類別,旦可以用來描述資料的結構比struct來的方便,可以是NULL,並具備繼承的能力。
public class employee 
{
    public string name;
    public string title;
}
調用方式如下:
protected void Page_Load(object sender, EventArgs e)
{
   employee ep = new employee();
   ep.name="東尼";
   ep.title="總裁";
}

使用Interface來建立型別

interface只能建構一個已實作該介面的類別物件,通常我們稱它為「介面」
interface ISampleInterface
{
    void SampleMethod();
}

class ImplementationClass : ISampleInterface
{   
    void ISampleInterface.SampleMethod()
    {
        // Method implementation.
    }

    static void Main()
    {
        // Declare an interface instance.
        ISampleInterface obj = new ImplementationClass();

        // Call the member.
        obj.SampleMethod();
    }
}

使用enum來建立型別

enum 關鍵字用來宣告列舉,是包含一組稱為列舉程式清單之具名常數的不同類型。
public class EnumTest
{
    enum Days { Sun, Mon, Tue, Wed, Thu, Fri, Sat };

    static void Main()
    {
        int x = (int)Days.Sun;
        int y = (int)Days.Fri;
        Console.WriteLine("Sun = {0}", x);
        Console.WriteLine("Fri = {0}", y);
    }
}
/* Output:
   Sun = 0
   Fri = 5
*/