如何使用自定义属性应用正则表达式 [英] How to apply regular expression using custom attributes

查看:86
本文介绍了如何使用自定义属性应用正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要实现自定义属性级别属性它采用正则表达式,并验证属性值.另外,我应该能够在用户界面级别的TextBox中应用此正则表达式.

我想将正则表达式实现为属性,因为数据可能并不总是来自UI,有时对象可能会从服务中填充.因此,我只想在一个位置存储正则表达式.

类似这样的东西.什么是实现此目的的最佳方法.

public class "d {6}" ]

受保护的 字符串帐户编号

获取

设置

" d {9}" ]

受保护的 字符串 RoutingNumber

获取

设置

解决方案

如果您打算通过Reflection读取属性,则您的应用可能运行缓慢,也可能运行缓慢.取决于您调用Validation属性的频率.最好简单地定义一个类,AccountNumber或RoutingNumber,该类实现一些包含Validate方法之类的通用接口.

"一个类应该知道如何处理本身;

换句话说,就是将智能元件内置到对象中.每次使用该对象时,它就已经知道该怎么做,您不必坐在那里重新设计正确的Regex字符串……只要您或下一个人记得添加该属性即可.

Rudy = 8 ^ D


I want to implement custom property level attributes which takes regular expression, and validates the property value. Also, I should be able to apply this regular expression in UI level TextBox.

I want to implement Regular Expression as attribute because, the data may not always be coming from UI, some time the object may get populated from service. So I would like to have only one place to store regular expression.

Some thing like this. What would be the best way to implement this.

 

public class Account

    {

        [Validate("d{6}"]

        protected string AccountNumber

        {

            get;

            set;

        }

        [Validate("d{9}"]

        protected string RoutingNumber

        {

            get;

            set;

        }

    }

解决方案

And if you plan to read the attribute through Reflection, your app may or may not run sluggishly.  Depends upon how often you call upon the Validation attribute.  It might be better to just simply define a class, AccountNumber or RoutingNumber, that implement some common interface that included a Validate method or something.

"A class should know how to take care of itself; no more, no less."

In other words, build the smarts into the object.  Everytime you use the object, it already knows how to do that stuff and you don't have to sit there and re-figure out the correct Regex string....provided you or the next person remembers to add the attribute.  How would you enforce the attribute being added, anyway?

Rudy  =8^D


这篇关于如何使用自定义属性应用正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆