使用Regex Inside Property Setter

时间:2013-12-20 21:27:30

标签: c#-4.0

我需要知道如何组合属性和正则表达式。这是属性:

public string NameFormal        
{       
    get {return nameFormal;}    
    set     
    {   
        nameFormal = value;
    }   
}

我想使用setter来使用我已经拥有的正则表达式模式来验证输入。我可以写一个单独的bool函数给是/否匹配。但是如何在返回字符串的属性中执行此操作?感谢帮助。

我正在使用VS2010。

1 个答案:

答案 0 :(得分:0)

假设您想要在设置器中设置它之前检查正则表达式的值?

public string NameFormal        
{       
    get {return nameFormal;}    
    set     
    {   
        string pattern = "^\\d{3}-\\d{3}-\\d{4}$"; //input your regex here
        if (Regex.IsMatch(value, pattern))
        {
            nameFormal = value;
        }
        else
        {
            //didn't match
        }
    }   
}

小心将这样的逻辑放入setter中,因为在设置属性时它可能会让人感到困惑而且它会无声地失败,我建议投掷或有一些事情提醒用户/程序员设置此变量失败。

相关问题