如何获取DefaultValueAttribute属性的默认值,下面提供一个Demo来说明实现这个功能
首先声明一个类MyTest
using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
using System.Windows.Forms;
using System.Drawing;
namespace ProperTyGridApplication
{
[DefaultProperty("Text")]
public class MyTest
{
private string _ControlID;
[PropertyTab("s")]
[Bindable(true)]
[Browsable(true)]
[DefaultValue(125)]
public string ControlID
{
get { return _ControlID; }
set { _ControlID = value; }
}
private bool _Needcheck;
[PropertyTab("s")]
[Bindable(true)]
[Browsable(true)]
public bool Needcheck
{
get { return _Needcheck; }
set { _Needcheck = value; }
}
private ControlTypeEnum _ControlType = ControlTypeEnum.Label;
[PropertyTab("s")]
[Bindable(true)]
[Browsable(true)]
public ControlTypeEnum ControlType
{
get { return _ControlType; }
set { _ControlType = value; }
}
public enum ControlTypeEnum
{
/**/
/// <summary>
/// 标签
/// </summary>
Label = 1,
/**/
/// <summary>
/// 文本框
/// </summary>
TextBox = 2,
ComboBox=3,
CheckBox=4
}
private ListItemCollection _ValueList = new ListItemCollection();
[PropertyTab("s")]
[Bindable(true)]
[Browsable(true)]
public ListItemCollection ValueList
{
get { return _ValueList; }
set { _ValueList = value; }
}
private Font font;
[PropertyTab("s")]
[Bindable(true)]
[Browsable(true)]
public Font FontTest {
set { font = value; }
get { return font; }
}
private DateTime dt;
[PropertyTab("s")]
[Bindable(true)]
[Browsable(true)]
public DateTime DateTest
{
set {
dt = value;
}
get {
return dt;
}
}
private int intTest;
[Category("Value")]
[Bindable(System.ComponentModel.BindableSupport.Default,System.ComponentModel.BindingDirection.OneWay)]
[Browsable(true)]//是否显示
[Description("this is a num")]
[DefaultValue(20)]
public int IntTest
{
set {
intTest = value;
}
get {
return intTest;
}
}
}
}
我们通过下面的Code来获取IntTest的 [DefaultValue(20)]值
AttributeCollection attributes = TypeDescriptor.GetProperties(new MyTest())["IntTest"].Attributes;
DefaultValueAttribute myAttribute = (DefaultValueAttribute)attributes[typeof(DefaultValueAttribute)];
this.Text = myAttribute.Value.ToString();