我在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;
}
}
}
我哪里错了?