1

如何将 Text 的默认值设置为“abc”?

public enum MessageType
{
    Good,
    Bad
}

public partial class Message : System.Web.UI.UserControl
{
    public bool Visible { get; set; }       // Is the error visible
    public string Text { get; set; }        // Text of the error message
    public MessageType Type { get; set; }   // Message type

    protected void Page_Load(object sender, EventArgs e)
    {
        ErrorPanel.Visible = this.Visible;
        ErrorMsg.Text = this.Text;

        // Hide if nothing to display
        if (this.Text == null)
                this.Visible = false;

        // Set correct CSS class
        if (this.Type == MessageType.Good)
            ErrorPanel.CssClass = "good-box";
        else
            ErrorPanel.CssClass = "bad-box";
    }
}
4

3 回答 3

3

也许您可以使用声明属性的老派

private string _Text = "abc";

public string Text
{
   get { return _Text; }
   set { _Text = value; }
}
于 2011-04-11T09:30:56.397 回答
3

您可以向属性添加 DefaultValue 属性吗?

例如:

[System.ComponentModel.DefaultValue( "abc" )]
public string Text {get;set;}
于 2011-04-11T09:31:47.147 回答
0

我相信最好的地方是在类的构造函数中

或者

private string _Text;    
public string Text
{
   get { return _Text ?? "Your Default"; }
   set { _Text = value; }
}

编辑

DefaultValueAttribute 不会导致成员使用属性值自动初始化。您必须在代码中设置初始值。

来自 MSDN

于 2011-04-11T09:53:30.010 回答