2009-09-26 42 views
0

我想添加一个正则表达式到静态类的nattribute。有没有什么办法让静态正则表达式类和使用属性?

[正则表达式(MyRegex.DecimalRegEx)

从类:

public static class MyRegex 
    {   
     public static string Decimal_Between_1_And_100 
     { 
      get 
      { 
       return (@"^\s*\d+(\.\d{1,2})?\s*$");   
      } 
     }   
    } 

我知道属性需要一个const VAL - 有没有办法解决这?

感谢

戴维

回答

0

您可以指定MyRegEx类的类型,而不是正则表达式的实例,下面是想法。

public interface IRegexProvider 
{ 
    Regex Regex { get; } 
} 

public class RegularExpressionAttribute : Attribute 
{ 
    public readonly Type _factory; 

    public RegularExpressionAttribute(Type regexFactory) 
    { 
     _factory = regexFactory; 
    } 

    public Regex Regex 
    { 
     get 
     { 
      // you can cache this 
      var factory = (IRegexProvider)Activator.CreateInstance(_factory); 
      return factory.Regex; 
     } 
    } 
} 

// using 

public class MyRegex : IRegexProvider 
{   
    public Regex Regex 
    { 
     get 
     { 
      return new Regex(@"^\s*\d+(\.\d{1,2})?\s*$");   
     } 
    }   
} 

[RegularExpression(typeof(MyRegex))] 
+0

谢谢 - 你试过吗?它不编译 - 不能分配属性到泛型? – Davy 2009-09-26 20:33:06

+0

我不厌倦编译它(没有VS可用),现在已经修复了。上面的版本现在编译。 – 2009-09-27 07:25:07

+0

谢谢谢谢 - 我应该早些发布这个,但我试图用DataAnnotations这个也有,有没有什么方法可以使用这个isset期望一个字符串? - 对此很陌生。 – Davy 2009-09-27 13:53:15

2

这是不可能的正则表达式的一个实例添加到一个属性,因为正如你所说的,属性参数必须是常量。无法解决此限制,因为它是CLR/CLI的限制。

你可以做的最好的是把字符串值转换为属性构造函数中引擎盖下的正则表达式。

public class RegularExpressionAttribute : Attribute { 
    public readonly string StringValue; 
    public readonly Regex Regex; 
    public RegularExpressionAttribute(string str) { 
    StringValue = str; 
    Regex = new Regex(str); 
    } 
} 
相关问题