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
には、まったく同じオブジェクトへの参照が含まれています。 dates
でAdd
メソッドを呼び出すのは、Calendar1.SelectedDates
で呼び出すのと同じです(逆も同様)。
Calendar1.SelectedDates
を2番目のコード(コンパイルしない)で再割り当てできなかった理由は、あなたが言ったように、SelectedDatesは読み取り専用としてマークされているからです。
メンバーを読み取り専用としてマークすると、そのメンバーがただちにまたはクラス/ struct/etcのコンストラクターにのみ割り当てられることを意味します。
ただし、そのオブジェクト内のデータを変更することはできません。今から
はそれにそれの要素を変更することはできませんクラスReadOnlyCollectionは、あり
だけでいくつかの追加情報です。
たとえば、読み取り専用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
これらの回答はすばらしく、私を助けました。私はすべてを答えにすることができれば幸いです。再度、感謝します。 – CptSupermrkt