为什么不能只读使用属性 [英] Why can't readonly be used with properties

查看:93
本文介绍了为什么不能只读使用属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么C#中的属性不能为只读?

Why properties in C# cannot be readonly ?

当我尝试使属性为只读时,它指出:

When I try to have a property readonly it states that:


修饰符只读对此项目无效

a modifier 'readonly' is not valid for this item

在这里提出了类似的问题:
为什么属性不能为只读?
但是5年前提出了一个问题,然后提供的答案是:因为他们认为没有通过。 5年后是否仍然如此?

Simmilar question was asked here: Why can't properties be readonly? But the question was asked 5 years ago, and the answer provided then was: Because they didn't think it thru. Is this still the case after 5 years?

编辑:
代码示例:

edit: Code example:

public class GreetingClass
{
    public readonly string HelloText { get; set; }
}


推荐答案

属性在C#,实现只是不使用readonly关键字:

Properties can be readonly in C#, the implementation is just not using the readonly keyword:

如果使用C#6(VS 2015),则可以使用以下行,该行允许在

If you use C#6 (VS 2015) you can use the following line, which allows assigning the property in either the constructor or in the member definition.

public int Property { get; }

如果您使用的是较旧的C#/ Visual Studio版本,则可以编写类似的代码并分配构造函数中的字段或字段定义:

If you use an older C# / Visual Studio Version you can write something like this, and assign the field in the constructor or the field definition:

private readonly int property;
public int Property { get { return this.property; }}

这篇关于为什么不能只读使用属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆