自动属性值和默认值

Jos*_*ech 8 c# default-value

可能重复:
如何为C#Auto-Property提供默认值?

我有一个像这样的类的财产

public String fontWeight { get; set; }
Run Code Online (Sandbox Code Playgroud)

我希望它的默认值是 "Normal"

有没有办法以"自动"样式而不是以下方式执行此操作

public String fontWeight {
    get { return fontWeight; } 
    set { if (value!=null) { fontWeight = value; } else { fontWeight = "Normal"; } }
}
Run Code Online (Sandbox Code Playgroud)

Lee*_*ith 13

是的你可以.

如果您正在寻找类似的东西:

[DefaultValue("Normal")]
public String FontWeight
{
    get;
    set;
}
Run Code Online (Sandbox Code Playgroud)

谷歌搜索'使用.NET的面向方面编程'

..如果这样做太过分了:

private string fontWeight;
public String FontWeight {
    get
    {
        return fontWeight ?? "Normal";
    }
    set {fontWeight = value;} 
}
Run Code Online (Sandbox Code Playgroud)


Guf*_*ffa 10

不,自动属性只是一个普通的getter和/或setter和一个后备变量.如果要在属性中放置任何类型的逻辑,则必须使用常规属性语法.

但是,您可以使用??运算符使其缩短:

private string _fontWeight;

public String FontWeight {
  get { return _fontWeight; } 
  set { _fontWeight = value ?? "Normal"; }
}
Run Code Online (Sandbox Code Playgroud)

请注意,setter不用于初始化属性,因此如果未在构造函数中设置值(或在变量声明中指定值),则默认值仍为null.你可以在getter中进行检查而不是解决这个问题:

private string _fontWeight;

public String FontWeight {
  get { return _fontWeight ?? "Normal"; } 
  set { _fontWeight = value; }
}
Run Code Online (Sandbox Code Playgroud)