当我6-8年前在大学时,我了解到使用Java时,通常的做法是使用公共get和set方法,但使用私有变量。但是现在,当我使用C#时,我意识到许多常见的类变量具有公共可访问性,例如string.length减
C#中的常见做法是将变量公之于众(人们可以通过这种方式进行编程,这是普遍接受的吗?)
由于
答案 0 :(得分:2)
String.Length实际上不是一个公共变量。在C#中,以这种方式使用getter是很常见的:
class Foo
{
private int _bar;
public int Bar
{
get { return _bar; } // getter
set { _bar = value; } // setter
}
}
// ...
Foo foo = new Foo();
foo.Bar = 42;
换句话说,string.Length只是只读变量string._lengh的getter。
答案 1 :(得分:1)
通常,将setter
标记为private
也是一种很好的做法,这意味着只有声明了setter的位置才能设置属性的值,以及任何其他派生类可以使用getter方法访问它。
因此,有两种方法可以声明属性:
使用prop
快捷方式并按Tab键两次(Visual Studio中的代码段)。这会产生:
public int Foo{ get; set; }
使用propg
快捷键+ Tab两次将setter声明为private。看起来像这样:
public int Foo{ get; private set; }
使用快捷方式propfull
完整实施,它将为您提供:
private int Foo;
public int MyProperty
{
get { return Foo;}
set { Foo = value;}
}
答案 2 :(得分:0)
您也可以只读取公共变量,而不是将其设置为私有:
class Foo
{
public readonly int Bar; // Bar can only be initialized in the constructor
public Foo()
{
this.Bar = 42;
}
}