aba*_*hev 59 .net c# msdn properties readonly
我在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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
我哪里错了?
Jon*_*eet 100
下面的答案是在2010年写的.在C#6(2015年发布)中,您可以编写只读自动实现的属性:
// This can only be assigned to in a constructor
public int Foo { get; }
Run Code Online (Sandbox Code Playgroud)
你是绝对正确的.目前不可能正确地执行只读自动实现的属性.让setter私有不是一回事,不管有些书和MSDN可能会说:)
如果我统治世界,情况就不是这样了.当我在6月看到NDC 2010的一些语言设计师时(请一起来!)我打算试图说服,贿赂,哄骗,并且一般会对自己造成麻烦,直到他们同意为止.毕竟,这只是一个薄薄的功能.
看一下那篇MSDN文章,文本本身并没有说它创建了一个只读的自动属性.它使用自动属性创建一个不可变类型,这是正确的.唯一有问题的是评论说
// Read-only properties.
Run Code Online (Sandbox Code Playgroud)
......这绝对是错的.该框架与我们一致:
var prop = typeof(Contact).GetProperty("Name");
Console.WriteLine(prop.CanWrite); // Prints True
Run Code Online (Sandbox Code Playgroud)
这令人困惑.您应该将只读区分为c#readonly
(关键字的含义).
readonly
:你只能在构造函数中写入它,然后永远不会更多. 归档时间: |
|
查看次数: |
27176 次 |
最近记录: |