结合code合同和正则表达式同和、正则表达式、code

2023-09-03 22:43:57 作者:情场通缉犯

所以我有一个非常简单的类有一个字符串属性。此字符串必须具有一定的图案。我试图执行本使用code合同。这个类看起来是这样的:

So I have a very simple class with one string as property. This string has to have a certain pattern. I'm trying to enforce this using code contracts. The class looks something like this:

class SimpleClass
{
    public Property { get; set; }

    public SimpleClass(string prop)
    {
      Contract.Requires(IsValid(prop));
      this.Property = prop;
    }

    [ContractInvariantMethod]
    void ObjectInvariant()
    {
      Contract.Invariant(IsValid(Property));
    }

    bool IsValid(string arg)
    {
      // Use regex to check if arg is a valid string
    }
}

非常简单。然而,这将引发无法读取异常,另一个说,'会员SimpleClass.IsValid比封闭的方法SimpleClass。#构造函数(System.String)能见度不足。这是为什么违法?我应该复制/正则表达式粘贴到这两种方法?这似乎是右侧相反。请帮助我了解!

Very straightforward. However, this throws an unreadable exception and another one saying that 'Member SimpleClass.IsValid has less visibility than the enclosing method SimpleClass.#ctor(System.String)'. Why is this illegal? Should I copy/paste the regex into both methods? That seems to be the opposite of right. Please help me understand!

推荐答案

另一种方式是避免原始痴迷,并使用适合你的目的的一类,例如:

Another way is avoid 'primitive obsession' and use a class tailored to your purpose, e.g.:

public SimpleClass(Email address)
{
    // no need to check, it must be valid :)
}

...然后封装在Email类中的所有的验证逻辑。你仍然有关于验证字符串格式的问题,但我认为这是一个更好的成语是创建一个名为方法 Email.TryParse ,与时尚它沿行 int.TryParse 的。

... and then encapsulate all your validation logic in the Email class. You'll still have the "string format" issues about validation, but I think a better idiom for this is to create a method called Email.TryParse, and fashion it along the lines of int.TryParse.