我在 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 assigned to (except in a constructor or a variable initializer)
this.Bar = b;
}
}
}
我哪里错了?
最佳答案
下面的答案写于 2010 年。在 C# 6(2015 年发布)中,您可以编写只读自动实现的属性:
// This can only be assigned to in a constructor
public int Foo { get; }
你完全正确。正确只读自动实现的属性目前是不可能的。将 setter 设为私有(private)不是一回事,不管某些书籍和 MSDN 怎么说:)
如果我统治世界,情况就不会如此。当我在 NDC 2010 看到一些语言设计者时在 6 月(请一起来!)我打算尝试说服、贿赂、哄骗并通常对自己造成滋扰,直到他们同意为止。毕竟,这只是一个极薄的特性。
看看那篇 MSDN 文章,文本本身并没有说它创建了一个只读的自动属性。它使用自动属性创建了一个不可变类型,这是正确的。唯一有问题的是评论说
// Read-only properties.
...这绝对是错误的。该框架同意我们的观点:
var prop = typeof(Contact).GetProperty("Name");
Console.WriteLine(prop.CanWrite); // Prints True
关于c# - 只读自动实现的属性是否可能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2480503/