C#中DefaultValueAttribute的使用

首先說明

DefaultValueAttribute是指定屬性 (Property) 的默認值。

命名空間:System.ComponentModel
程序集:System(在 system.dll 中)

比如我們這樣寫:

    public class PrintInfo
    {
        [DefaultValue(typeof(string), "555")]
        public string UserName { get; set; }
    }
那麼要想得到這個555並不是用
string _UserName=new PrintInfo().UserName;
而應該這樣寫:

            AttributeCollection attrColl = TypeDescriptor.GetProperties(new PrintInfo())["UserName"].Attributes;
            DefaultValueAttribute attr = attrColl[typeof(DefaultValueAttribute)] as DefaultValueAttribute;
            string _Value = attr.Value;

這個時候_Value的值爲555,如果用上面的方法得到的_UserName的值依然爲NULL。具體我也說不明白,但是在一個屬性上面加上這個Attribute,很會讓人誤解。

參見:http://msdn.microsoft.com/zh-cn/library/system.componentmodel.defaultvalueattribute(VS.80).aspx


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章