ASP.NET 3.5 properties' private member access within class
I have read about how in ASP.NET 3.5 you can declare properties in C#
public DateTime DisplayDate
{
get;
}
instead of
private DateTime _displayDate
public DateTime DisplayDate
{
get {return _displayDate;}
}
like this post explains.
My question is, within the class, how do I access the private variable?
For example instead of this
public MyClass(DateTime myDisplayDate)
{ _displayDate = myDisplayDate; }
What should I assign to? Is it the public property?
public MyClass(DateTime myDisplayDate)
{ DisplayDate = myDisplayDate; }
开发者_运维技巧
Is this Correct?
public DateTime DisplayDate
{
get; private set;
}
public MyClass(DateTime myDisplayDate)
{
this.DisplayDate = myDisplayDate;
}
Automatic Properties like this (which aren't limited to ASP.NET) are there so you don't have to deal with the private field. If you want to set the property's value, use the property itself and add a private setter (so only your class can set it)
public DateTime DisplayDate
{
get;
private set;
}
You always need to declare both the getter and the setter with c# 3.0 automatic properties - see the other answers - the trick is to mark the setter as private.
public Foo { get; private set; }
精彩评论