[英]C# 6 getters and setters
I am using C# 6.0 to create getters and setters of properties in a class like this: 我正在使用C#6.0在类中创建属性的getter和setter:
private int _id { get; set; }
public int Id => _id;
But the compiler says: 但是编译器说:
Property or indexer 'Id' cannot be assigned to -- it is read only
无法将属性或索引器“Id”分配给 - 它是只读的
How can I fix it without creating getters and setters like this: 如何在不创建这样的getter和setter的情况下修复它:
private int _id { get; set; }
public int Id
{
get { return this._id; }
set { this._id = value; }
}
Shorthand syntax with => only constructs a read-only property. 使用=>的简写语法只构造一个只读属性。
private int _id;
public int Id => _id;
This is equivalent to auto-property which is read-only: 这相当于auto-property,它是只读的:
public int Id { get; }
If you want your property to be both settable and gettable, but publically only gettable, then define private setter: 如果您希望您的属性既可设置又可获取,但公开只能获取,那么定义私有的setter:
public int Id { get; private set; }
That way you don't need any private field. 这样你就不需要任何私人领域了。
With 同
private int _id { get; set; }
you are creating a property _id
with a getter and a setter. 您正在使用getter和setter创建属性
_id
。
With 同
public int Id => _id;
You are creating a property Id
that has only a getter and returns the value of property _id
您正在创建仅具有getter的属性
Id
并返回property _id
的值
I think you are mixing up how to take advantage of automatic properties, because this 我认为你正在混淆如何利用自动属性,因为这
private int _id { get; set; }
public int Id
{
get { return this._id; }
set { this._id = value; }
}
creates two properties: _id
with auto-generated getter/setter and Id
with explicit getter/setter that just call the corresponding getter/setter of _id
. 创建两个属性:带有自动生成的getter / setter的
_id
和带有显式getter / setter的Id
,它只调用_id
的相应getter / setter。
Without the automatic property feature, you had to write this: 没有自动属性功能,你必须写这个:
private int _id;
public int Id
{
get { return this._id; }
set { this._id = value; }
}
Here, _id
is a field and Id
is a property. 这里,
_id
是一个字段, Id
是一个属性。
This is the C# 7.0 syntax, just in case you want to keep the private field: 这是C#7.0语法,以防您想要保留私有字段:
public int Id
{
get => _id;
set => _id = value;
}
private int _id;
Which is very useful for giving full access to some of the properties of a wrapped object: 这对于完全访问包装对象的某些属性非常有用:
private Person wrappedObject;
public string Name
{
get => wrappedObject.Name;
set => wrappedObject.Name = value;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.