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:
So you'll have to either:
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.