![](/img/trans.png)
[英]How to pass the name of variable to a function and return its value in C#?
[英]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;
這個問題似乎是相關的,但我無法讓它發揮作用。
這可能嗎? 如果是這樣,它會怎么做?
三個選項來做你想做的事:
static
關鍵字創建 static 屬性/字段 另外值得注意的是,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.