是只读的自动实现的属性可能吗? [英] Is read-only auto-implemented property possible?
问题描述
我发现一个话题MSDN 的那个会谈,是的,这是可能的。
I found a topic on MSDN that talks that yes, this is possible.
我做了一个测试,这似乎打破了这个说法:
I did a test that seems to break this statement:
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;
}
}
}
我在哪里错了?
Where am I wrong?
推荐答案
下面写早在2010年在C#6的答案(被释放,2015年),你的可以的写只读自动-implemented属性:
The answer below was written back in 2010. In C# 6 (to be released in 2015) you can write read-only automatically-implemented properties:
// This can only be assigned to in a constructor
public int Foo { get; }
您说的没错。正确的只读自动实现的属性,目前是不可能的。使得二传手私人是不一样的东西,不管什么一些书籍和MSDN可能会说的:)
You're absolutely right. Properly read-only automatically implemented properties are currently impossible. Making the setter private isn't the same thing, regardless of what some books and MSDN might say :)
如果我统治的时代,这将不会是这样。当我看到一些语言的设计者在 NDC 2010 六月(请走吧!)我打算劝说,贿赂,哄着,一般使我自己滋扰,直到他们同意。这只是一个极薄的功能,毕竟。
If I ruled the world, this would not be the case. When I see some of the language designers at NDC 2010 in June (please come along!) I intend to try to persuade, bribe, cajole and generally make a nuisance of myself until they agree. It's just one wafer-thin feature, after all.
望着那MSDN文章,文字本身不说,它创建了一个只读的自动性。它创建了一个不可变的类型的使用的自动属性,这是正确的。唯一的问题位是说评论
Looking at that MSDN article, the text itself doesn't say that it creates a read-only automatic property. It creates an immutable type using an automatic property, and that's correct. The only problematic bits are the comments saying
// Read-only properties.
...这是绝对错误的。该框架同意我们:
... which are definitely wrong. The framework agrees with us:
var prop = typeof(Contact).GetProperty("Name");
Console.WriteLine(prop.CanWrite); // Prints True
这篇关于是只读的自动实现的属性可能吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!