现在的位置: 首页 > 综合 > 正文

C#中DefaultValueAttribute的使用

2014年01月22日 ⁄ 综合 ⁄ 共 647字 ⁄ 字号 评论关闭

首先说明

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


抱歉!评论已关闭.