close

修飾詞其實也算是一個很重要的東西

但也有人說他不是很重要

只要全部用public(公開)就好了 XD

不過他這樣說  我也覺得沒錯啦

但其實他是扮演著一些防止錯誤的一種機制

當然再深入講解時  

就讓我們先來看看有哪些宣告類型成員存取範圍的修飾詞吧

public class Sample
{
    // 公開 任何人都可以使用
    public              int A;

    // 私人 只有自己可以使用 
    // (就是只能在Sample這Class中才能使用)
    private             int B;

    // 保護 只有自己及繼承這Class的人才能使用
    protected           int C;

    // 內部 只能在相同專案中使用
    internal            int D;

    // 保護內部 只有相同專案且只有自己及繼承的人可以使用
    protected internal  int E;
}

如果看完上面的解釋還是不明白的話

你可以接著往下看

public

public class Test : MonoBehaviour
{
    // Use this for initialization
    void Start()
    {
        // 宣告Class Sample 並實體化
        Sample sample = new Sample();
        // A 就是public公開成員 所以我們可以把他點出來使用
        sample.A = 10;
    }
}

private

public class Test : MonoBehaviour
{
    // Use this for initialization
    void Start()
    {
        // 宣告Class Sample 並實體化
        Sample sample = new Sample();
        // B private(私有) 所以這段會是
錯誤 點不出來的
        sample.
B = 10;
    }
}

這邊通常很多人會有疑問  那為什麼要用私有的

其實只主要是防止一些錯誤的事發生

範例

public class Sample2
{
    // 實體化時代參數 並傳入你的編號
    public Sample2(int Number)
    {
        this._Number = Number;
    }

    // 存儲編號 私有使用
    private int _Number;

    // 用屬性的方式 只能取 不能修改
    public int Number
    {
        get
        {
            return _Number;
        }
    }
}

進行測試

public class Test : MonoBehaviour
{
    // Use this for initialization
    void Start()
    {
        // 宣告Class Sample2 並實體化 傳入編號參數
        Sample2 sample = new Sample2(1);
        // 直接印出編號 = 1
        Debug.Log(sample.Number);
    }
}

那這個編號是不可以被更改的

有可能這些編號代表一些重要的資訊

為了防止你不小心忘記或是其他人使用時不小心改到

 

protected

public class Test : MonoBehaviour
{
    // Use this for initialization
    void Start()
    {
        // 宣告Class Sample
        Sample sample = new Sample();

        // protected(保護) 你能在繼承或私有中使用
        // 所以這是錯誤的
        sample.C = 10;
    }
}

正確方式

// 繼承Sample 如果對繼承不了解 請查閱(8) C# 繼承
public class Test : Sample
{
    // Use this for initialization
    void Start()
    {
        // 不需要再宣告 直接使用此變數
        C = 10;
    }
}

internal

這我就不用程式來講解了

基本上網路很多都在亂說這只能在相同的namespace

其實這是不正確的

他是只能在相同的內部組件才能使用

講白一點就是要同一個專案

如果你是在VS使用的話  可能還有機會感受到

但在Unity中  你都是在同一個專案  所以這個對你來說幾乎用不到

但如果你是使用別人封裝好的dll檔  可能你就會明白了

如果你還是不明白

沒關係 基本上Unity製作遊戲中 你不會使用到的!!

(應該吧 呵呵

 

arrow
arrow
    創作者介紹
    創作者 Weight 的頭像
    Weight

    股市Coding

    Weight 發表在 痞客邦 留言(0) 人氣()