簡體   English   中英

Getter和Setter作為函數?

[英]Getters and Setters as functions?

因此,我知道在C ++中應該使用GET和SET函數從其他位置訪問變量。 但是,在C#中,這似乎是一個屬性。 所以我的問題是我不應該為GET和SET使用函數,而是在Unity3d中使用c#樣式嗎?

目前,我的代碼如下所示:

/// <summary>
/// Highest tempruture during the different weathers. 
/// </summary>
[SerializeField]
protected float _fHighestTemp;

/// <summary>
/// This is our GET function for reading the value. 
/// </summary>
public float GetHighestTemp() { return _fHighestTemp; }

/// <summary>
/// This is our SET function this one we use to set the highest temprature we could have during different weather. 
/// </summary>
public void SetHighestTemp(float SetHighestTemp) { _fHighestTemp = SetHighestTemp; }

將其與函數一起使用是否有不利之處? (更多的內存占用,或者其他任何原因)並且如果不能,為什么最好使用c#方式代替其屬性?

很抱歉遇到這個菜鳥問題,但是我真的很想知道,在我以錯誤的方式進入Unity項目之前,必須回去重新做一遍。

在最新版本的C#中,我記不清哪個屬性的getter和setter作為自動實現的屬性語法的捷徑。

這個

protected int MyInt{get;set;}

相當於

protected int _MyInt;
protected int GetMyInt(){return _MyInt;}
protected void SetMyInt(int value){_MyInt=value;}

這個

private int MyInt{get;set;}

相當於

private int _MyInt;
private int GetMyInt(){return _MyInt;}
private void SetMyInt(int value){_MyInt=value;}

以下內容也有效:

public int MyInt{get;}
public int MyInt2{set;}
public int MyInt3{get;set myMethod(value);}
public int MyInt4{get{return myMethod();}}

屬性是C#中訪問器的慣用表示,因此,應該使用它們。 您可以實現自己的屬性訪問器方法,也可以使用自動屬性。

暫無
暫無

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

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