Getters和Setters作为功能?

时间:2014-05-07 02:09:38

标签: c# unity3d

所以我在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#方式而不是它的属性?

对于noob问题我很抱歉,但在我以错误的方式进入Unity项目之前我真的想知道,并且必须重新进行重做。

2 个答案:

答案 0 :(得分:0)

在最近的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();}}

答案 1 :(得分:0)

属性是C#中访问器的惯用表示,所以是的,你应该使用它们。您可以实现自己的属性访问器方法或使用自动属性。