簡體   English   中英

C# 使 class 返回其實例而不帶 function 或變量

[英]C# Make a class return its instance without a function or variable

因此,我在 Unity 中使用具有單個實例的類已經有一段時間了,通常這樣做:

class PublicThings {
    public static PublicThings I; // instance of this class
    public int Score;
    void Start { I = GetComponent<PublicThings>(); }
}

用法: PublicThings.I.Score = 10;

效果很好。 但是,我一直很好奇是否可以返回 class 的實例而無需在 class 之后鍵入.I

所以基本上這就是它的外觀:

PublicThings.Score = 10;

這個問題似乎是相關的,但我無法讓它發揮作用。

這可能嗎? 如果是這樣,它會怎么做?

三個選項來做你想做的事:

  1. 在 PublicThings class 中使用static關鍵字創建 static 屬性/字段
  2. 制作一個ScriptableObject並將其附加到調用它的項目(視頻教程
  3. 利用Singleton 模式(我建議在嘗試其他兩種方法之前避免使用這種方法)

另外值得注意的是,Singleton 模式不一定能解決您的問題。 你仍然需要調用PublicThings.instance.Score類的東西。

希望這可以幫助。

Singleton 模式是 go 的方式。
此外,使用惰性實例化。

public class PublicThings
{
    private static PublicThings _instance;

    // Your private constructor
    private PublicThings() { }

    public static PublicThings Instance
    {
        get
        {
            if (_instance == null)
            {
                // Construction of instance logic here
                _instance = new PublicThings();
            }

            return _instance;
        }
        // No setter, read-only property
    }

    // Decide if Score is a read-only property or not.
    public int Score { get; set; }
}

當需要PublicThings的單個實例時,它將被構造並存儲。 對實例的第二次訪問將提供已存儲的訪問。

[Test]
public void WithTwoAccess_ToSingleInstance_MustBeTheSame()
{
    var things1 = PublicThings.Instance;
    var things2 = PublicThings.Instance;

    Assert.AreSame(things2, things1);
    // Asserts true
}

如果您的Score屬性必須設置一次,只需將 que Instance屬性更改為需要Score值的方法(通常稱為GetInstance )。

希望能幫助到你。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM