質問

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:

    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. 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).

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.

他のヒント

If you actually read the documentation, you'll see an exception is thrown by Point.Parse() in three situations:

  • source is not composed of two comma- or space-delimited double values.
  • 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.
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top