C#: Difference between using System.Text and System.Text.RegularExpressions

前端 未结 3 1254
渐次进展
渐次进展 2021-01-27 14:22

In an ASP.NET C# application, I noticed in order to use Regex and StringBuilder, I had to put both

using System.Text;
using System.Text.RegularExpressions;


        
相关标签:
3条回答
  • 2021-01-27 14:39

    From MSDN:

    The System.Text namespace contains classes that represent ASCII and Unicode character encodings; abstract base classes for converting blocks of characters to and from blocks of bytes; and a helper class that manipulates and formats String objects without creating intermediate instances of String.

    And:

    The System.Text.RegularExpressions namespace contains classes that provide access to the .NET Framework regular expression engine. The namespace provides regular expression functionality that may be used from any platform or language that runs within the Microsoft .NET Framework. In addition to the types contained in this namespace, the System.Configuration.RegexStringValidator class enables you to determine whether a particular string conforms to a regular expression pattern.

    StringBuilder lives in the System.Text namespace and Regex lives in System.Text.RegularExpressions. These namespaces are just logical separators, and including a parent namespace doesn't automatically include children, and vice versa.

    0 讨论(0)
  • 2021-01-27 14:48

    They are different namespaces with different classes. Including the top level namespace (System.Text) doesn't mean that namespace below (like RegularExpression) will be added.

    StringBuilder is from System.Text so that is why you need using System.Text; and Regex is from System.Text.RegularExpressions and that is why you need that as well.

    See: using directive from C# Specifications section 9.4.

    The scope of a using-directive extends over the namespace-member-declarations of its immediately containing compilation unit or namespace body. The scope of a using-directive specifically does not include its peer using-directives. Thus, peer using-directives do not affect each other, and the order in which they are written is insignificant.

    0 讨论(0)
  • 2021-01-27 14:49
    • Regex is defined in System.Text.RegularExpressions
    • StringBuilder is defined in System.Text

    You need to include both namespaces for these two types to be in scope. Including a namespace A.B doesn't automatically include a contained namespace A.B.C. If this were the case, nested namespaces would be of limited use.

    0 讨论(0)
提交回复
热议问题