我在MSDN上发现了一个话题,是的,这是可能的.
我做了一个似乎打破了这个声明的测试:
using System;
namespace Test
{
class Program
{
static void Main(string[] args)
{
Foo f = new Foo("1");
Console.WriteLine(f.Bar); // prints 1
f.Test("2");
Console.WriteLine(f.Bar);// successfully prints 2
}
}
class Foo
{
public Foo(string b)
{
this.Bar = b;
}
public string Bar { get; private set; }
public void Test(string b)
{
// this would be impossible for readonly field!
// next error would be occur: CS0191 or CS0191
// A readonly field cannot be …Run Code Online (Sandbox Code Playgroud) 我的项目包含大量具有属性的类,其后备字段标记为只读,因为它们仅在构造时设置.作为一种风格问题,我喜欢使用自动属性,因为它消除了大量的样板代码,并鼓励使用属性成员而不是支持字段.但是,当使用自动属性时,我失去了我的支持字段的"readonly-ness".我知道当字段以这种方式标记时,编译器/运行时能够利用一些性能增强,所以我希望能够将我的auto-property标记为readonly,如下所示:
[ReadOnly]
public string LastName { get; }
Run Code Online (Sandbox Code Playgroud)
而不是
private readonly string _LastName;
public string LastName
{
get
{
return _LastName;
}
}
Run Code Online (Sandbox Code Playgroud)
有没有一些机制可以做到这一点?如果没有,自定义支持字段的性能增益是否真的值得?
我认为,将该字段公开为公共是另一种选择,以这种方式公开字段似乎是错误的.即
public readonly string LastName;
Run Code Online (Sandbox Code Playgroud) 我只是想知道c#不支持只读和只写自动属性的逻辑原因.
(即我的意思是只有get或set的属性,但不是两者.如果你试图定义这样的自动属性,你会得到一个编译器错误,告诉你自动属性必须同时具有get和set).
是否只是为了阻止人们不小心忘记添加一个?
谢谢