SelectedDatesCollection 作为属性是只读的,但您仍然可以将其更改为对象,如添加或删除项目。
更改对象(也就是通过更改数据调用它的方法)和更改对象引用本身、作为类的成员等之间是有区别的。
通过做:
SelectedDatesCollection dates = Calendar1.SelectedDates;
您不是在复制集合,而只是保存它的引用,就像给它取另一个名字一样。
最终,您还可以这样做:
protected void Page_Load(object sender, EventArgs e)
{
Calendar1.SelectedDates.Add(new DateTime(2012, 5, 1));
Calendar1.SelectedDates.Add(new DateTime(2012, 5, 5));
Calendar1.SelectedDates.Add(new DateTime(2012, 5, 9));
}
只是有人会说另一种方式更具可读性。
dates
并Calendar1.SelectedDates
包含对完全相同对象的引用。调用Add
方法dates
就像调用它一样Calendar1.SelectedDates
,反之亦然。
正如您所说,您尝试在第二段代码(不编译)中执行操作时无法重新分配的原因Calendar1.SelectedDates
是 SelectedDates 被标记为只读。
将成员标记为只读仅仅意味着它只会被立即分配或在类/结构/等的构造函数中分配。
但是,这并不意味着您不能更改该对象中的数据。
从现在开始,这只是一些额外的信息
有一个类 ReadOnlyCollection,它不允许更改它的 ELEMENTS。
因此,例如,拥有只读 ReadOnlyCollection 将意味着您无法更改成员,也无法更改元素。
例子:
public class Class1
{
public List<int> Numbers = new List<int> {1, 2, 3};
}
public class Class2
{
public readonly List<int> Numbers = new List<int> {1, 2, 3};
}
public class Class3
{
public ReadOnlyCollection<int> Numbers = new ReadOnlyCollection<int> {1, 2, 3};
}
public class Class3
{
public readonly ReadOnlyCollection<int> Numbers = new ReadOnlyCollection<int> {1, 2, 3};
}
差异:
var c1 = new Class1();
var c2 = new Class2();
var c3 = new Class3();
var c4 = new Class4();
c1.Numbers = new List<int> {4, 5, 6}; // Works
c1.Numbers.Clear(); // Works
c2.Numbers = new List<int> {4, 5, 6}; // Error
c2.Numbers = c2.Numbers; // Error - you just can't reassign it!
c2.Numbers.Clear(); // Works - you are just calling the Clear method of the existing list object.
c3.Numbers = new ReadOnlyCollection<int> {4, 5, 6}; // Works - the member is not readonly
// ReadOnlyCollection doesn't allow to change it's elements after initializing it.
// It doesn't even have these functions:
c3.Numbers.Clear(); // Error
c3.Numbers.Add(); // Error
c3.Numbers.Remove(2); // Error
c4.Numbers = new ReadOnlyCollection<int> {4, 5, 6}; // Error - the member is marked as readonly
// ReadOnlyCollection doesn't allow to change it's elements after initializing it.
// It doesn't even have these functions:
c4.Numbers.Clear(); // Error
c4.Numbers.Add(); // Error
c4.Numbers.Remove(2); // Error