也许这只是一个误解,但对我来说这是一个很大的问题.让我来解释一下:
根据参考,属性是机制而不是字段.一种为字段提供读写函数的机制,根据这种机制,我们可以使用get和set访问器创建只读,只写或读写属性.
现在实现在这里:
public class Foo
{
private List<string> _bar;
public List<string> Bar
{
get
{
return _bar;
}
}
public Foo()
{
_bar = new List<string>();
_bar.Add("string1");
}
}
Run Code Online (Sandbox Code Playgroud)
在Foo类中,我们有一个只读属性(Bar),它由一个字符串组成.
现在让我们为这个类添加一个驱动程序:
static void Main(string[] args)
{
Foo fooObj = new Foo();
fooObj.Bar.Add("string2");
foreach (string s in fooObj.Bar)
{
Console.WriteLine(s);
}
Console.ReadLine();
}
Run Code Online (Sandbox Code Playgroud)
这是一个很大的问号:
为什么Bar财产不是只读的?
输出:
srring1
string2
Run Code Online (Sandbox Code Playgroud)
我知道如何创建一个只读集合(我的问题不是为什么List<T>不是只读的),我需要一个关于只读属性的解释.