我在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-03-20 04:51:37
下面的答案是在2010年写的。在C# 6(2015年发布)中,您可以编写自动实现的只读属性:
// This can only be assigned to in a constructor
public int Foo { get; }
你说的完全正确。自动实现的只读属性目前是不可能的。将setter设为私有并不是一回事,不管一些书籍和MSDN可能会说什么:)
如果我统治世界,情况就不会是这样了。当我6月份在NDC 2010上看到一些语言设计师时(请跟我来!)我打算试着说服、贿赂、哄骗,让自己成为一个讨厌鬼,直到他们同意为止。毕竟,这只是一个薄薄的功能。
看看那篇MSDN文章,文本本身并没有说它创建了一个只读的自动属性。它使用自动属性创建一个不可变的类型,这是正确的。唯一有问题的是评论说
// Read-only properties.
..。这绝对是错的。该框架与我们的观点一致:
var prop = typeof(Contact).GetProperty("Name");
Console.WriteLine(prop.CanWrite); // Prints True
发布于 2010-03-20 04:56:08
该属性在Foo
类外部是只读的。我想这就是文章所要表达的意思。
但这与使用readonly
关键字标记变量不同。
发布于 2010-03-20 04:55:26
Private set与readonly
不同。
与方法或字段类似,private
关键字使setter的可见性仅对类本身可用。其他对象不能使用setter,但类本身的方法可以自由调用它。因此,您的测试代码可以很好地编译和工作。
它对外部对象显示为readonly
属性,但在真正的定义中不是只读的。
https://stackoverflow.com/questions/2480503
复制相似问题