C#中应用定制特性来进行运行期判断

定制特性本质上还是一个类,只不过CLR规定定制特性必须继承自Attribute类

定制特性可以应用在类,属性,方法等对象(几乎是元数据中的所有成员)上面

当应用定制特性的时候,是生成了特性的一个实例(按照应用时在特性后面的括号内戴上的命名参数和定位参数),并且将应用的对象和特性关联在一起,这个是体现在文件的元数据中的(编译器会将特性的实例序列化到元数据中)

 

下面是一个例子,首先定义一个特性类用来表示文本的长度限制,然后定义一个实体类,并且在实体类的属性上应用该特性,最后在运行的时候动态检测实体类实例的所有应用的特性,并且根据特性来检验实体的成员的长度是否超过特性定义的长度。

 

//特性类

[AttributeUsage(AttributeTargets.All, AllowMultiple=true, Inherited=true)]
    public class InputCheckEntityAttribute : Attribute
    {
        private int m_nMaxLength = 10;
        public int MaxLength
        {
            get { return m_nMaxLength; }
            set { m_nMaxLength = value; }
        }
    }

 

  //实体类

    public class EntityToCheck
    {
        private string m_input = string.Empty;
        [InputCheckEntityAttribute(MaxLength = 8)]
        public string Input
        {
            get { return m_input; }
            set
            {
                object[] attrs = this.GetType().GetProperty("Input").GetCustomAttributes(typeof(InputCheckEntityAttribute), true);                              
                foreach(object obj in attrs)
                {
                    Attribute attr = obj as Attribute;
                    if (attr.GetType().Name == "InputCheckEntityAttribute")
                    {
                        int maxLen = (attr as InputCheckEntityAttribute).MaxLength;
                        if (value.Length > maxLen)
                        {
                            throw(new Exception(string.Format("字段Input的最大长度不能超过{0}", maxLen)));
                        }
                    }
                }
            }
        }
    }

 

//测试入口函数

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void buttonVal_Click(object sender, EventArgs e)
        {
            EntityToCheck entity = new EntityToCheck();
            entity.Input = txtVal.Text.Trim();
        }
    }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值