C#正则表达式中.Match().Value和Match().ToString()的区别是什么?

3

I have the following code:

Match matcher = new Regex("[0-9]+.[0-9]+.[0-9]+").Match("12/02/1994");

if (matcher.Success)
{
   string matchedString1 = matcher.Value;
   string matchedString2 = matcher.ToString();
}

在这种情况下,matchedString1matchedString2包含相同的值"12/02/1994"。对于任何正则表达式,matcher.Valuematcher.ToString()是否总是返回相同的结果?

ToString()通常被实现为返回一些有助于在调试窗口中使用、连接对象等方面有用的内容。 - Miserable Variable
是的,我决定使用matcher.Value。对我来说它“看起来更好”。 - Guido
是的,“Value” 的使用意图很清晰。 - Miserable Variable
2个回答

5

Match类是从Group类派生而来,而Group类又是从Capture类派生而来。

Capture类使用以下代码重写了ToString()方法:

[__DynamicallyInvokable, TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
public override string ToString()
{
    return this.Value;
}

所以,是的,它是相同的值。

2

来自MSDN;

Capture.Value属性;

从输入字符串中获取捕获的子字符串。

Capture.ToString()方法。

通过调用Value属性从输入字符串中检索捕获的子字符串。

即使我们查看.NET Reflector,也可以看到Capture类重写了ToString()方法,如下所示;

[__DynamicallyInvokable, TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
public override string ToString()
{
    return this.Value;
}

所以,是的。它们具有相同的值。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接