C#自動屬性與自定義構造方法範例

本篇介紹自動屬性與自定義構造方法的概念,並實作範例。

自動屬性(Auto-Implemented Properties)

自動實作的屬性,在 C# 3.0 及更新版本中,當屬性存取子中不需要額外的邏輯時,自動實作的屬性可讓屬性宣告變得更精簡。它們還可讓用戶端程式碼建立物件。當您宣告屬性時,如下列範例所示,編譯器會建立私用、匿名的支援欄位,但只能透過屬性的 get 和 set 存取子才能存取。

C#6-自動屬性也可以在建立時直接賦予初始值,例如:

public string FirstName { get; set; } = "Jane";

自定義構造方法

構造方法為初始化對象的方法,而自定義的構造方法則可以在初始化對象時,讓對象執行構造方法內的成員。此外,也可以對構造方法進行傳遞方法參數


範例:

using UnityEngine;
using System.Collections;
using System;

public class Student
{
    /*
    自動屬性:比原來屬性更快的表達式,表達式同時含有字段跟屬性的功能

    private int age;
    public int Age
    {
        get
        {
            return age;
        }
        set
        {
            age = value;
        }
    }

    等同於 public int age { get; set; }
    */

    public int age { get; set; }
    public string name { get; set; }

    //自訂構造函數,當對象初始化時即可執行函數內成員
    public Student(int age, string name)
    {
        //this 關鍵字所指的是類別 (Class) 的目前執行個體 (Instance)
        this.age = age; //this.age為class中字段age
        this.name = name; //this.name為class中字段name
        Say();
    }

    public void Say()
    {
        Debug.Log("姓名是 "+ name + "年齡是 "+ age);
    }
}

public class CodingTest : MonoBehaviour
{
    void Start()
    {
        Student a = new Student(18, "James");
        Student b = new Student(20, "Howard");
    }
}

輸出結果
Auto-Implemented Properties


參考網址:
https://msdn.microsoft.com/zh-tw/library/bb384054.aspx

 

對「C#自動屬性與自定義構造方法範例」的想法

發表留言