[英]how can i check that string variable represent a point struct?
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()
在以下三种情况下引发了异常:
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. string.IndexOf()
和string.Substring()
(或RegEx.Match()
)和double.TryParse()
,但是基本上是在重建Point.Parse()
并可以更好地返回new Point { X = parsedX, Y = parsedY }
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.