RoR*_*RoR 33 c# syntax properties
这些是Person类的声明.
protected int ID { get; set; }
protected string Title { get; set; }
protected string Description { get; set; }
protected TimeSpan jobLength { get; set; }
Run Code Online (Sandbox Code Playgroud)
我如何使用get/set?主要是,我实例化了一个
Person Tom = new Person();
Run Code Online (Sandbox Code Playgroud)
Tom.set/get怎么样?
我习惯于做C++风格,你只需写出int getAge()和void setAge()函数.但是在C#中有快捷方式处理get和set?
Jon*_*eet 73
假设您有权访问它们(您声明的属性protected),您可以像这样使用它们:
Person tom = new Person();
tom.Title = "A title";
string hisTitle = tom.Title;
Run Code Online (Sandbox Code Playgroud)
这些是属性.它们基本上是一对getter/setter方法(虽然你可以只有一个getter,或者只是一个setter),并带有适当的元数据.您给出的示例是自动实现的属性,其中编译器正在添加支持字段.您可以自己编写代码.例如,Title您声明的属性是这样的:
private string title; // Backing field
protected string Title
{
get { return title; } // Getter
set { title = value; } // Setter
}
Run Code Online (Sandbox Code Playgroud)
...除了支持字段被赋予"无法形容的名称" - 您无法在C#代码中引用.你被迫通过房产.
您可以使财产的一部分比另一部分更受限制.例如,这很常见:
private string foo;
public string Foo
{
get { return foo; }
private set { foo = value; }
}
Run Code Online (Sandbox Code Playgroud)
或作为自动实施的财产:
public string Foo { get; private set; }
Run Code Online (Sandbox Code Playgroud)
这里的"getter"是公开的,但"setter"是私有的.