Automatic Property Values and Defaults [duplicate]
Possible Duplicate:
How do you give a C# Auto-Property a default value?
I have a property in a class like so
public Stri开发者_运维问答ng fontWeight { get; set; }
I want it's default to be of "Normal"
Is there a way to do this in "automatic" style rather than the following
public String fontWeight {
get { return fontWeight; }
set { if (value!=null) { fontWeight = value; } else { fontWeight = "Normal"; } }
}
Yes you can.
If your looking for something like:
[DefaultValue("Normal")]
public String FontWeight
{
get;
set;
}
Do a google search for 'Aspect Oriented Programming using .NET'
..if this is overkill for you do this:
private string fontWeight;
public String FontWeight {
get
{
return fontWeight ?? "Normal";
}
set {fontWeight = value;}
}
No, an automatic property is just a plain getter and/or setter and a backing variable. If you want to put any kind of logic in the property, you have to use the regular property syntax.
You can use the ??
operator to make it a bit shorter, though:
private string _fontWeight;
public String FontWeight {
get { return _fontWeight; }
set { _fontWeight = value ?? "Normal"; }
}
Note that the setter is not used to initialise the property, so if you don't set the value in the constructor (or assign a value in the variable declaration), the default value is still null. You could make the check in the getter instead to get around this:
private string _fontWeight;
public String FontWeight {
get { return _fontWeight ?? "Normal"; }
set { _fontWeight = value; }
}
You will need to use a backing field.
private string fontWeight;
public String FontWeight
{
get { String.IsNullOrEmpty(fontWeight) ? "Normal" : fontWeight;}
set {fontWeight = String.IsNullOrEmpty(value) ? "Normal" : value;}
}
You either need to use a backing field and initialize that to your default value
private String fontWeight = "Normal";
public String FontWeight
{
get { return fontWeight; }
set { fontWeight = value; }
}
or, keep the auto property and call the setter in your constructor
public constructor()
{
FontWeight = "Normal";
}
public String FontWeight { get; set; }
One way to do it is using PostSharp as detailed in this answer to a similar question.
You could use the DefaultValue attribute:
[DefaultValue("Normal")]
public string FontWeight { get; set; }
Although it notes that
A DefaultValueAttribute will not cause a member to be automatically initialized with the attribute's value. You must set the initial value in your code.
so you could use this in conjunction with initialisation in the constructor or via a backing field and default handling.
You'd need either a variable like so:
string fontWeight;
public string FontWeight
{
get
{
if (string.IsNullOrEmpty(fontWeight))
fontWeight = "Normal";
return fontWeight;
}
set { fontWeight = value; }
}
Or use a Constructer
to set an initial value:
class FontClass
{
public string FontWeight { get; set; }
public FontClass()
{
FontWeight = "Normal";
}
}
精彩评论