Mos*_*afa 1 automatic-properties c#-3.0
目前我正在使用.Net 3.0,但我不知道如何使用自动属性.
例如,如果我想通过Authomatic Properties编写此示例代码,我该怎么办?
private string _name = string.Empty;
private string _family = string.Empty;
//A field with default value
private DateTime _releaseDate = System.DateTime.Now;
//ReadOnly Property
public string Name
{
get {return _name; }
}
//enforce validation rules on setting
public string Family
{
get { _family; }
set
{
if (value.Length < 3)
return new Exception("Family need at least 3 character long");
else
_family = value;
}
}
// A property from two other fields
public string FullName
{
get { return _name + " " + _family; }
}
Run Code Online (Sandbox Code Playgroud)
谢谢大家的回复,我得到了答案
你不能.
自动属性只是为您创建一个私有支持字段,并将其隐藏.如果您需要在您的财产中拥有逻辑,您应该自己实施.
使用自动属性,您必须同时具有getter和setter,但您可以将setter设为私有,例如:
public string Foo { get; private set; }
Run Code Online (Sandbox Code Playgroud)
顺便说一句,您不能从字符串属性返回异常.应该抛出异常,而不是返回.
public string Family
{
get { _family; }
set
{
if (value.Length < 3)
return new Exception("Family need at least 3 character long");
else
_family = value;
}
}
Run Code Online (Sandbox Code Playgroud)
这应该是:
public string Family
{
get { _family; }
set
{
if (value.Length < 3)
throw new Exception("Family need at least 3 character long");
else
_family = value;
}
}
Run Code Online (Sandbox Code Playgroud)