简体   繁体   English

我如何检查该字符串变量表示一个点结构?

[英]how can i check that string variable represent a point struct?

Point.Parse("SomeText");

how can i check if the given string represent a point ? 如何检查给定的字符串是否表示一个点?

Parse Method Documentation is Here 解析方法文档在这里

The fastest, and probably cleanest way to achieve this is by implementing your own TryParse method for Point.Parse : 实现此目标的最快且可能最干净的方法是为Point.Parse实现自己的TryParse方法:

    public bool TryParse(string source, out Point point)
    {
        try
        {
            point = Point.Parse(source);
        }
        catch (FormatException ex)
        {
            point = default(Point);
            return false;
        }

        return true;
    }

Which you can then consume like so: 然后可以像这样消费:

        Point point;
        if (!TryParse("12, 13", out point))
        {
            // We have an invalid Point!
        }

If your string isn't a valid point, the method will return false and you can do whatever needs to be done right away. 如果您的字符串不是有效的点,则该方法将返回false,并且您可以立即做任何需要做的事情。 The out parameter will contain the parsed Point if the parse succeeded, and will otherwise contain the default value for Point , which is probably (0, 0). 如果解析成功,则out参数将包含已解析的Point ,否则将包含Point的默认值,该默认值可能是(0,0)。

Do note that the exception is being supressed here, but that shouldn't give you any trouble. 请注意,这里例外已被禁止,但这不会给您带来任何麻烦。 If need be, you can re-throw it after setting point . 如果需要,您可以在设置point之后将其重新抛出。

If you actually read the documentation, you'll see an exception is thrown by Point.Parse() in three situations: 如果您确实阅读了文档,则会看到Point.Parse()在以下三种情况下引发了异常:

  • source is not composed of two comma- or space-delimited double values. source不是由两个逗号或空格分隔的double值组成。
  • source does not contain two numbers. 源不包含两个数字。
  • source contains too many delimiters. 源包含太多定界符。

So you'll have to either: 因此,您必须:

  • Make sure your input represents a point and you don't pass bogus information to the method. 确保您的输入代表一个点,并且不要将虚假信息传递给该方法。 We don't know where your input comes from, so that's up to you. 我们不知道您的输入来自哪里,所以这取决于您。
  • Validate your input, for example using a regular expression. 验证您的输入,例如使用正则表达式。 This may harm performance more than not validating, but that depends on the input and how often the input actually doesn't represent a point. 这可能会比不进行验证更多地损害性能,但这取决于输入以及输入实际上不代表点的频率。
  • Parse each string yourself, for example using string.IndexOf() and string.Substring() (or RegEx.Match() ) and double.TryParse() , but then you're basically rebuilding Point.Parse() and can better return a new Point { X = parsedX, Y = parsedY } anyway. 自己解析每个字符串,例如,使用string.IndexOf()string.Substring() (或RegEx.Match() )和double.TryParse() ,但是基本上是在重建Point.Parse()并可以更好地返回new Point { X = parsedX, Y = parsedY }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM