C#中DefaultValueAttribute的使用

来源:互联网 发布:肖八肖四选择题 知乎 编辑:程序博客网 时间:2024/06/06 03:06

首先说明

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