与 List 结合使用时是否违反只读关键字?
例如
class Program
{
public List<string> InputList;
public List<string> DefaultList;
public readonly List<string> ReadOnlyList;
public Program()
{
InputList = new List<string>() { "Initialized String" };
DefaultList = InputList;
ReadOnlyList = InputList;
}
static void Main(string[] args)
{
var p = new Program();
p.SampleMethod();
Console.ReadKey();
}
private void SampleMethod()
{
Console.WriteLine("inputList - " + InputList.LastOrDefault());
Console.WriteLine("readOnlyList - " + ReadOnlyList.LastOrDefault());
Console.WriteLine("defaultList - " + DefaultList.LastOrDefault());
InputList.Add("Modified String");
Console.WriteLine("inputList - " + InputList.LastOrDefault());
Console.WriteLine("readOnlyList - " + ReadOnlyList.LastOrDefault());
Console.WriteLine("defaultList - " + DefaultList.LastOrDefault());
}
}
和打印的输出
inputList - Initialized String
readOnlyList - Initialized String
defaultList - Initialized String
inputList - Modified String
readOnlyList - Modified String
defaultList - Modified String
readonly 的概念是,它的值只能在构造函数内部更改,如果它没有被初始化。所以在上面的例子中,当两个集合在运行时更改时,ReadOnlyList 和 DefaultList 之间的确切区别是什么。
而且我也发现将 ReadOnlyList 更改为 IReadOnlyCollection 没有任何区别。有人可以帮助我理解这个概念。