在C#属性中,'值是'变量定义?在任何地方定义之前,我都可以看到它在setter的主体中使用。
namespace TestBindings
{
public class Dog
{
private decimal age;
private string name;
private const int AgeFactor = 7;
public Dog(decimal age, string name)
{
this.age = age;
this.name = name;
}
public decimal AgeDogYears
{
get { return age / AgeFactor; }
set { age = value * AgeFactor; }
}
public decimal AgeHumanYears
{
get { return age; }
set { age = value; } //here
}
public string Name
{
get { return name; }
set { name = value; } // and here
}
}
}
答案 0 :(得分:1)
'价值'变量自动从use-site传入,并且是set表达式中传递的值的预定义变量名。
e.g。
var jack = new Dog(13, "jack");
jack.Name = "Jackson";
此处=符号后的值将被传递到类中定义的setter中,作为' value'。
public string Name
{
get { return name; }
set { name = value; } //here
}
它大致相当于它取代了具有显式getter和setter方法的Java表达式,只是使用不同的语法来统一设置字段和属性。
e.g。
public class Dog {
private double age;
private String name;
private final int AgeFactor = 7;
public Dog(double age, String name) {
this.age = age;
this.name = name;
}
public double getAgeHumanYears() {
return age;
}
public void setAgeHumanYears(double value) {
this.age = value;
}
public double getAgeDogYears() {
return age / AgeFactor;
}
public void setAgeDogYears(double value) {
age = value * AgeFactor;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
我们的测试更改为。
private Dog jack = new Dog(13, "jack");
jack.setName("Jackson");