文章内容

2017/3/8 13:56:20,作 者: 黄兵

C#中DefaultValueAttribute的使用

首先说明

DefaultValueAttribute是指定属性 (Property) 的默认值。

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

比如我们这样写:

[csharp] view plain copy
 print?
  1. public class PrintInfo  
  2. {  
  3.     [DefaultValue(typeof(string), "555")]  
  4.     public string UserName { getset; }  
  5. }  

那么要想得到这个555并不是用

[csharp] view plain copy
 print?
  1. string _UserName=new PrintInfo().UserName;  

而应该这样写:

[csharp] view plain copy
 print?
  1. AttributeCollection attrColl = TypeDescriptor.GetProperties(new PrintInfo())["UserName"].Attributes;  
  2. DefaultValueAttribute attr = attrColl[typeof(DefaultValueAttribute)] as DefaultValueAttribute;  
  3. string _Value = attr.Value;  


这个时候_Value的值为555,如果用上面的方法得到的_UserName的值依然为NULL。具体我也说不明白,但是在一个属性上面加上这个Attribute,很会让人误解。

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

转载自:csdn-JRoger_

分享到:

发表评论

评论列表