Regex.CompileToAssembly 方法  
定义
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
编译正则表达式并将其保存到单个程序集中的磁盘。
重载
| CompileToAssembly(RegexCompilationInfo[], AssemblyName, CustomAttributeBuilder[], String) | 
		已过时.
	 将一个或多个指定的 Regex 对象和指定的资源文件编译为具有指定属性的命名程序集。 | 
| CompileToAssembly(RegexCompilationInfo[], AssemblyName) | 
		已过时.
	 将一个或多个指定的 Regex 对象编译为命名程序集。 | 
| CompileToAssembly(RegexCompilationInfo[], AssemblyName, CustomAttributeBuilder[]) | 
		已过时.
	 将一个或多个指定的 Regex 对象编译为具有指定属性的命名程序集。 | 
注解
注意
在 .NET Core 和 .NET 5+ 上,对 Regex.CompileToAssembly 方法的调用将引发 PlatformNotSupportedException。 不支持写出程序集。
CompileToAssembly(RegexCompilationInfo[], AssemblyName, CustomAttributeBuilder[], String)
- Source:
- Regex.cs
- Source:
- Regex.cs
- Source:
- Regex.cs
注意
Regex.CompileToAssembly is obsolete and not supported. Use the GeneratedRegexAttribute with the regular expression source generator instead.
将一个或多个指定的 Regex 对象和指定的资源文件编译为具有指定属性的命名程序集。
public:
 static void CompileToAssembly(cli::array <System::Text::RegularExpressions::RegexCompilationInfo ^> ^ regexinfos, System::Reflection::AssemblyName ^ assemblyname, cli::array <System::Reflection::Emit::CustomAttributeBuilder ^> ^ attributes, System::String ^ resourceFile);public static void CompileToAssembly (System.Text.RegularExpressions.RegexCompilationInfo[] regexinfos, System.Reflection.AssemblyName assemblyname, System.Reflection.Emit.CustomAttributeBuilder[]? attributes, string? resourceFile);[System.Obsolete("Regex.CompileToAssembly is obsolete and not supported. Use the GeneratedRegexAttribute with the regular expression source generator instead.", DiagnosticId="SYSLIB0036", UrlFormat="https://aka.ms/dotnet-warnings/{0}")]
public static void CompileToAssembly (System.Text.RegularExpressions.RegexCompilationInfo[] regexinfos, System.Reflection.AssemblyName assemblyname, System.Reflection.Emit.CustomAttributeBuilder[]? attributes, string? resourceFile);public static void CompileToAssembly (System.Text.RegularExpressions.RegexCompilationInfo[] regexinfos, System.Reflection.AssemblyName assemblyname, System.Reflection.Emit.CustomAttributeBuilder[] attributes, string resourceFile);static member CompileToAssembly : System.Text.RegularExpressions.RegexCompilationInfo[] * System.Reflection.AssemblyName * System.Reflection.Emit.CustomAttributeBuilder[] * string -> unit[<System.Obsolete("Regex.CompileToAssembly is obsolete and not supported. Use the GeneratedRegexAttribute with the regular expression source generator instead.", DiagnosticId="SYSLIB0036", UrlFormat="https://aka.ms/dotnet-warnings/{0}")>]
static member CompileToAssembly : System.Text.RegularExpressions.RegexCompilationInfo[] * System.Reflection.AssemblyName * System.Reflection.Emit.CustomAttributeBuilder[] * string -> unitPublic Shared Sub CompileToAssembly (regexinfos As RegexCompilationInfo(), assemblyname As AssemblyName, attributes As CustomAttributeBuilder(), resourceFile As String)参数
- regexinfos
- RegexCompilationInfo[]
描述要编译的正则表达式的数组。
- assemblyname
- AssemblyName
程序集的文件名。
- attributes
- CustomAttributeBuilder[]
一个数组,用于定义要应用于程序集的属性。
- resourceFile
- String
要包含在程序集中的 Win32 资源文件的名称。
- 属性
例外
              assemblyname 或 regexinfosnull。
              resourceFile 参数指定无效的 Win32 资源文件。
找不到由 resourceFile 参数指定的文件。
仅 .NET Core 和 .NET 5+ :不支持创建已编译正则表达式的程序集。
注解
              CompileToAssembly(RegexCompilationInfo[], AssemblyName, CustomAttributeBuilder[], String) 方法生成一个 .NET Framework 程序集,其中 regexinfos 数组中定义的每个正则表达式由类表示。 通常,CompileToAssembly(RegexCompilationInfo[], AssemblyName, CustomAttributeBuilder[], String) 方法是从生成已编译正则表达式程序集的单独应用程序中调用的。 程序集中包含的每个正则表达式具有以下特征:
- 它派生自 Regex 类。 
- 它分配由其相应 RegexCompilationInfo 对象的 - fullnamespace和- name参数定义的完全限定名称。
- 它具有默认的(或无参数)构造函数。 
通常,实例化和使用已编译正则表达式的代码位于独立于创建程序集的代码的程序集或应用程序中。
由于 CompileToAssembly 方法从方法调用生成 .NET Framework 程序集,而不是使用特定语言的类定义关键字(如 C# 中的 class 或 Visual Basic 中的 Class...End Class),因此不允许使用开发语言的标准属性语法将 .NET Framework 属性分配给程序集。 
              attributes 参数提供了用于定义应用于程序集的属性的替代方法。 对于要应用于程序集的每个属性,请执行以下操作:
- 创建表示要调用的属性构造函数的参数类型的 Type 对象的数组。 
- 检索表示要应用于新程序集的属性类的 Type 对象。 
- 调用属性 Type 对象的 GetConstructor 方法,以检索表示要调用的属性构造函数的 ConstructorInfo 对象。 传递表示构造函数参数类型的 Type 对象的数组 GetConstructor 方法 
- 创建一个 Object 数组,该数组定义要传递给特性构造函数的参数。 
- 通过将构造函数传递给步骤 3 中检索的 ConstructorInfo 对象以及步骤 4 中创建的 Object 数组来实例化 CustomAttributeBuilder 对象。 
然后,可以将这些 CustomAttributeBuilder 对象的数组而不是 attributes 参数传递给 CompileToAssembly(RegexCompilationInfo[], AssemblyName, CustomAttributeBuilder[], String) 方法。
调用方说明
如果要在安装了 .NET Framework 4.5 或其点版本的系统上进行开发,则以 .NET Framework 4 为目标,并使用 CompileToAssembly(RegexCompilationInfo[], AssemblyName) 方法创建包含已编译正则表达式的程序集。 尝试在该程序集中使用具有 .NET Framework 4 的系统上的正则表达式之一会引发异常。 若要解决此问题,可以执行以下操作之一:
- 在安装了 .NET Framework 4 而不是更高版本的系统上生成包含已编译正则表达式的程序集。 
- 实例化 Regex 对象或调用正则表达式模式匹配方法时,使用静态或实例 Regex 方法与 Compiled 选项,而不是从程序集调用 CompileToAssembly(RegexCompilationInfo[], AssemblyName) 和检索编译的正则表达式。 
另请参阅
适用于
CompileToAssembly(RegexCompilationInfo[], AssemblyName)
- Source:
- Regex.cs
- Source:
- Regex.cs
- Source:
- Regex.cs
注意
Regex.CompileToAssembly is obsolete and not supported. Use the GeneratedRegexAttribute with the regular expression source generator instead.
将一个或多个指定的 Regex 对象编译为命名程序集。
public:
 static void CompileToAssembly(cli::array <System::Text::RegularExpressions::RegexCompilationInfo ^> ^ regexinfos, System::Reflection::AssemblyName ^ assemblyname);public static void CompileToAssembly (System.Text.RegularExpressions.RegexCompilationInfo[] regexinfos, System.Reflection.AssemblyName assemblyname);[System.Obsolete("Regex.CompileToAssembly is obsolete and not supported. Use the GeneratedRegexAttribute with the regular expression source generator instead.", DiagnosticId="SYSLIB0036", UrlFormat="https://aka.ms/dotnet-warnings/{0}")]
public static void CompileToAssembly (System.Text.RegularExpressions.RegexCompilationInfo[] regexinfos, System.Reflection.AssemblyName assemblyname);static member CompileToAssembly : System.Text.RegularExpressions.RegexCompilationInfo[] * System.Reflection.AssemblyName -> unit[<System.Obsolete("Regex.CompileToAssembly is obsolete and not supported. Use the GeneratedRegexAttribute with the regular expression source generator instead.", DiagnosticId="SYSLIB0036", UrlFormat="https://aka.ms/dotnet-warnings/{0}")>]
static member CompileToAssembly : System.Text.RegularExpressions.RegexCompilationInfo[] * System.Reflection.AssemblyName -> unitPublic Shared Sub CompileToAssembly (regexinfos As RegexCompilationInfo(), assemblyname As AssemblyName)参数
- regexinfos
- RegexCompilationInfo[]
描述要编译的正则表达式的数组。
- assemblyname
- AssemblyName
程序集的文件名。
- 属性
例外
              assemblyname 或 regexinfosnull。
仅 .NET Core 和 .NET 5+ :不支持创建已编译正则表达式的程序集。
示例
以下示例创建名为 RegexLib.dll的程序集。 该程序集包含两个已编译正则表达式。 第一个,Utilities.RegularExpressions.DuplicatedString,匹配两个相同的连续单词。 第二个字符串 Utilities.RegularExpressions.EmailAddress检查字符串的格式是否正确,是否为电子邮件地址。
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text.RegularExpressions;
public class RegexCompilationTest
{
   public static void Main()
   {
      RegexCompilationInfo expr;
      List<RegexCompilationInfo> compilationList = new List<RegexCompilationInfo>();
      // Define regular expression to detect duplicate words
      expr = new RegexCompilationInfo(@"\b(?<word>\w+)\s+(\k<word>)\b", 
                 RegexOptions.IgnoreCase | RegexOptions.CultureInvariant, 
                 "DuplicatedString", 
                 "Utilities.RegularExpressions", 
                 true);
      // Add info object to list of objects
      compilationList.Add(expr);
      // Define regular expression to validate format of email address
      expr = new RegexCompilationInfo(@"^(?("")(""[^""]+?""@)|(([0-9A-Z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9A-Z])@))" + 
                 @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9A-Z][-\w]*[0-9A-Z]\.)+[A-Z]{2,6}))$", 
                 RegexOptions.IgnoreCase | RegexOptions.CultureInvariant, 
                 "EmailAddress", 
                 "Utilities.RegularExpressions", 
                 true);
      // Add info object to list of objects
      compilationList.Add(expr);
                                             
      // Generate assembly with compiled regular expressions
      RegexCompilationInfo[] compilationArray = new RegexCompilationInfo[compilationList.Count];
      AssemblyName assemName = new AssemblyName("RegexLib, Version=1.0.0.1001, Culture=neutral, PublicKeyToken=null");
      compilationList.CopyTo(compilationArray); 
      Regex.CompileToAssembly(compilationArray, assemName);                                                 
   }
}
Imports System.Collections.Generic
Imports System.Reflection
Imports System.Text.RegularExpressions
Module RegexCompilationTest
   Public Sub Main()
      Dim expr As RegexCompilationInfo
      Dim compilationList As New List(Of RegexCompilationInfo)
          
      ' Define regular expression to detect duplicate words
      expr = New RegexCompilationInfo("\b(?<word>\w+)\s+(\k<word>)\b", _
                 RegexOptions.IgnoreCase Or RegexOptions.CultureInvariant, _
                 "DuplicatedString", _
                 "Utilities.RegularExpressions", _
                 True)
      ' Add info object to list of objects
      compilationList.Add(expr)
      ' Define regular expression to validate format of email address
      expr = New RegexCompilationInfo("^(?("")(""[^""]+?""@)|(([0-9A-Z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9A-Z])@))" + _
                 "(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9A-Z][-\w]*[0-9A-Z]\.)+[A-Z]{2,6}))$", _
                 RegexOptions.IgnoreCase Or RegexOptions.CultureInvariant, _
                 "EmailAddress", _
                 "Utilities.RegularExpressions", _
                 True)
      ' Add info object to list of objects
      compilationList.Add(expr)
                                             
      ' Generate assembly with compiled regular expressions
      Dim compilationArray(compilationList.Count - 1) As RegexCompilationInfo
      Dim assemName As New AssemblyName("RegexLib, Version=1.0.0.1001, Culture=neutral, PublicKeyToken=null")
      compilationList.CopyTo(compilationArray) 
      Regex.CompileToAssembly(compilationArray, assemName)                                                 
   End Sub
End Module
然后实例化并使用用于检查重复单词的字符串的正则表达式。
using System;
using Utilities.RegularExpressions;
public class CompiledRegexUsage
{
   public static void Main()
   {
      string text = "The the quick brown fox  fox jumps over the lazy dog dog.";
      DuplicatedString duplicateRegex = new DuplicatedString(); 
      if (duplicateRegex.Matches(text).Count > 0)
         Console.WriteLine("There are {0} duplicate words in \n   '{1}'", 
            duplicateRegex.Matches(text).Count, text);
      else
         Console.WriteLine("There are no duplicate words in \n   '{0}'", 
                           text);
   }
}
// The example displays the following output to the console:
//    There are 3 duplicate words in
//       'The the quick brown fox  fox jumps over the lazy dog dog.'
Imports Utilities.RegularExpressions
Module CompiledRegexUsage
   Public Sub Main()
      Dim text As String = "The the quick brown fox  fox jumps over the lazy dog dog."
      Dim duplicateRegex As New DuplicatedString()
      If duplicateRegex.Matches(text).Count > 0 Then
         Console.WriteLine("There are {0} duplicate words in {2}   '{1}'", _
            duplicateRegex.Matches(text).Count, text, vbCrLf)
      Else
         Console.WriteLine("There are no duplicate words in {1}   '{0}'", _
                           text, vbCrLf)
      End If
   End Sub
End Module
' The example displays the following output to the console:
'    There are 3 duplicate words in
'       'The the quick brown fox  fox jumps over the lazy dog dog.'
成功编译第二个示例需要引用 RegexLib.dll(第一个示例创建的程序集)添加到项目中。
注解
              CompileToAssembly(RegexCompilationInfo[], AssemblyName) 方法生成一个 .NET Framework 程序集,其中 regexinfos 数组中定义的每个正则表达式由类表示。 通常,CompileToAssembly(RegexCompilationInfo[], AssemblyName) 方法是从生成已编译正则表达式程序集的单独应用程序中调用的。 程序集中包含的每个正则表达式具有以下特征:
- 它派生自 Regex 类。 
- 它分配由其相应 RegexCompilationInfo 对象的 - fullnamespace和- name参数定义的完全限定名称。
- 它具有默认的(或无参数)构造函数。 
通常,实例化和使用已编译正则表达式的代码位于独立于创建程序集的代码的程序集或应用程序中。
调用方说明
如果要在安装了 .NET Framework 4.5 或其点版本的系统上进行开发,则以 .NET Framework 4 为目标,并使用 CompileToAssembly(RegexCompilationInfo[], AssemblyName) 方法创建包含已编译正则表达式的程序集。 尝试在该程序集中使用具有 .NET Framework 4 的系统上的正则表达式之一会引发异常。 若要解决此问题,可以执行以下操作之一:
- 在安装了 .NET Framework 4 而不是更高版本的系统上生成包含已编译正则表达式的程序集。 
- 实例化 Regex 对象或调用正则表达式模式匹配方法时,使用静态或实例 Regex 方法与 Compiled 选项,而不是从程序集调用 CompileToAssembly(RegexCompilationInfo[], AssemblyName) 和检索编译的正则表达式。 
另请参阅
适用于
CompileToAssembly(RegexCompilationInfo[], AssemblyName, CustomAttributeBuilder[])
- Source:
- Regex.cs
- Source:
- Regex.cs
- Source:
- Regex.cs
注意
Regex.CompileToAssembly is obsolete and not supported. Use the GeneratedRegexAttribute with the regular expression source generator instead.
将一个或多个指定的 Regex 对象编译为具有指定属性的命名程序集。
public:
 static void CompileToAssembly(cli::array <System::Text::RegularExpressions::RegexCompilationInfo ^> ^ regexinfos, System::Reflection::AssemblyName ^ assemblyname, cli::array <System::Reflection::Emit::CustomAttributeBuilder ^> ^ attributes);public static void CompileToAssembly (System.Text.RegularExpressions.RegexCompilationInfo[] regexinfos, System.Reflection.AssemblyName assemblyname, System.Reflection.Emit.CustomAttributeBuilder[]? attributes);[System.Obsolete("Regex.CompileToAssembly is obsolete and not supported. Use the GeneratedRegexAttribute with the regular expression source generator instead.", DiagnosticId="SYSLIB0036", UrlFormat="https://aka.ms/dotnet-warnings/{0}")]
public static void CompileToAssembly (System.Text.RegularExpressions.RegexCompilationInfo[] regexinfos, System.Reflection.AssemblyName assemblyname, System.Reflection.Emit.CustomAttributeBuilder[]? attributes);public static void CompileToAssembly (System.Text.RegularExpressions.RegexCompilationInfo[] regexinfos, System.Reflection.AssemblyName assemblyname, System.Reflection.Emit.CustomAttributeBuilder[] attributes);static member CompileToAssembly : System.Text.RegularExpressions.RegexCompilationInfo[] * System.Reflection.AssemblyName * System.Reflection.Emit.CustomAttributeBuilder[] -> unit[<System.Obsolete("Regex.CompileToAssembly is obsolete and not supported. Use the GeneratedRegexAttribute with the regular expression source generator instead.", DiagnosticId="SYSLIB0036", UrlFormat="https://aka.ms/dotnet-warnings/{0}")>]
static member CompileToAssembly : System.Text.RegularExpressions.RegexCompilationInfo[] * System.Reflection.AssemblyName * System.Reflection.Emit.CustomAttributeBuilder[] -> unitPublic Shared Sub CompileToAssembly (regexinfos As RegexCompilationInfo(), assemblyname As AssemblyName, attributes As CustomAttributeBuilder())参数
- regexinfos
- RegexCompilationInfo[]
描述要编译的正则表达式的数组。
- assemblyname
- AssemblyName
程序集的文件名。
- attributes
- CustomAttributeBuilder[]
一个数组,用于定义要应用于程序集的属性。
- 属性
例外
              assemblyname 或 regexinfosnull。
仅 .NET Core 和 .NET 5+ :不支持创建已编译正则表达式的程序集。
示例
以下示例创建一个名为 RegexLib.dll 的程序集,并将 AssemblyTitleAttribute 属性应用于该程序集。 该程序集包含两个已编译正则表达式。 第一个,Utilities.RegularExpressions.DuplicatedString,匹配两个相同的连续单词。 第二个字符串 Utilities.RegularExpressions.EmailAddress检查字符串的格式是否正确,是否为电子邮件地址。
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;
using System.Text.RegularExpressions;
public class RegexCompilationTest
{
   public static void Main()
   {
      RegexCompilationInfo expr;
      List<RegexCompilationInfo> compilationList = new List<RegexCompilationInfo>();
      // Define regular expression to detect duplicate words
      expr = new RegexCompilationInfo(@"\b(?<word>\w+)\s+(\k<word>)\b", 
                 RegexOptions.IgnoreCase | RegexOptions.CultureInvariant, 
                 "DuplicatedString", 
                 "Utilities.RegularExpressions", 
                 true);
      // Add info object to list of objects
      compilationList.Add(expr);
      // Define regular expression to validate format of email address
      expr = new RegexCompilationInfo(@"^(?("")(""[^""]+?""@)|(([0-9A-Z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9A-Z])@))" + 
                 @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9A-Z][-\w]*[0-9A-Z]\.)+[zA-Z]{2,6}))$", 
                 RegexOptions.IgnoreCase | RegexOptions.CultureInvariant, 
                 "EmailAddress", 
                 "Utilities.RegularExpressions", 
                 true);
      // Add info object to list of objects
      compilationList.Add(expr);
                                             
      // Apply AssemblyTitle attribute to the new assembly
      //
      // Define the parameter(s) of the AssemblyTitle attribute's constructor 
      Type[] parameters = { typeof(string) };
      // Define the assembly's title
      object[] paramValues = { "General-purpose library of compiled regular expressions" };
      // Get the ConstructorInfo object representing the attribute's constructor
      ConstructorInfo ctor = typeof(System.Reflection.AssemblyTitleAttribute).GetConstructor(parameters);
      // Create the CustomAttributeBuilder object array
      CustomAttributeBuilder[] attBuilder = { new CustomAttributeBuilder(ctor, paramValues) }; 
                                                         
      // Generate assembly with compiled regular expressions
      RegexCompilationInfo[] compilationArray = new RegexCompilationInfo[compilationList.Count];
      AssemblyName assemName = new AssemblyName("RegexLib, Version=1.0.0.1001, Culture=neutral, PublicKeyToken=null");
      compilationList.CopyTo(compilationArray); 
      Regex.CompileToAssembly(compilationArray, assemName, attBuilder);                                                 
   }
}
Imports System.Collections.Generic
Imports System.Reflection
Imports System.Reflection.Emit
Imports System.Text.RegularExpressions
Module RegexCompilationTest
   Public Sub Main()
      Dim expr As RegexCompilationInfo
      Dim compilationList As New List(Of RegexCompilationInfo)
          
      ' Define regular expression to detect duplicate words
      expr = New RegexCompilationInfo("\b(?<word>\w+)\s+(\k<word>)\b", _
                 RegexOptions.IgnoreCase Or RegexOptions.CultureInvariant, _
                 "DuplicatedString", _
                 "Utilities.RegularExpressions", _
                 True)
      ' Add info object to list of objects
      compilationList.Add(expr)
      ' Define regular expression to validate format of email address
      expr = New RegexCompilationInfo("^(?("")(""[^""]+?""@)|(([0-9A-Z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9A-Z])@))" + _ 
                 "(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9A-Z][-\w]*[0-9A-Z]\.)+[A-Z]{2,6}))$", _
                 RegexOptions.IgnoreCase Or RegexOptions.CultureInvariant, _
                 "EmailAddress", _
                 "Utilities.RegularExpressions", _
                 True)
      ' Add info object to list of objects
      compilationList.Add(expr)
      ' Apply AssemblyTitle attribute to the new assembly
      '
      ' Define the parameter(s) of the AssemblyTitle attribute's constructor 
      Dim params() As Type = { GetType(String) }
      ' Define the assembly's title
      Dim paramValues() As Object = { "General-purpose library of compiled regular expressions" }
      ' Get the ConstructorInfo object representing the attribute's constructor
      Dim ctor As ConstructorInfo = GetType(System.Reflection.AssemblyTitleAttribute).GetConstructor(params)
      ' Create the CustomAttributeBuilder object array
      Dim attBuilder() As CustomAttributeBuilder = { New CustomAttributeBuilder(ctor, paramValues) } 
                                                         
      ' Generate assembly with compiled regular expressions
      Dim compilationArray(compilationList.Count - 1) As RegexCompilationInfo
      Dim assemName As New AssemblyName("RegexLib, Version=1.0.0.1001, Culture=neutral, PublicKeyToken=null")
      compilationList.CopyTo(compilationArray) 
      Regex.CompileToAssembly(compilationArray, assemName, attBuilder) 
   End Sub
End Module
可以通过使用 ILDasm 等反射实用工具检查 AssemblyTitleAttribute 属性是否已应用于程序集。
然后实例化并使用用于检查重复单词的字符串的正则表达式。
using System;
using Utilities.RegularExpressions;
public class CompiledRegexUsage
{
   public static void Main()
   {
      string text = "The the quick brown fox  fox jumps over the lazy dog dog.";
      DuplicatedString duplicateRegex = new DuplicatedString(); 
      if (duplicateRegex.Matches(text).Count > 0)
         Console.WriteLine("There are {0} duplicate words in \n   '{1}'", 
            duplicateRegex.Matches(text).Count, text);
      else
         Console.WriteLine("There are no duplicate words in \n   '{0}'", 
                           text);
   }
}
// The example displays the following output to the console:
//    There are 3 duplicate words in
//       'The the quick brown fox  fox jumps over the lazy dog dog.'
Imports Utilities.RegularExpressions
Module CompiledRegexUsage
   Public Sub Main()
      Dim text As String = "The the quick brown fox  fox jumps over the lazy dog dog."
      Dim duplicateRegex As New DuplicatedString()
      If duplicateRegex.Matches(text).Count > 0 Then
         Console.WriteLine("There are {0} duplicate words in {2}   '{1}'", _
            duplicateRegex.Matches(text).Count, text, vbCrLf)
      Else
         Console.WriteLine("There are no duplicate words in {1}   '{0}'", _
                           text, vbCrLf)
      End If
   End Sub
End Module
' The example displays the following output to the console:
'    There are 3 duplicate words in
'       'The the quick brown fox  fox jumps over the lazy dog dog.'
成功编译第二个示例需要引用 RegexLib.dll(第一个示例创建的程序集)添加到项目中。
注解
              CompileToAssembly(RegexCompilationInfo[], AssemblyName, CustomAttributeBuilder[]) 方法生成一个 .NET Framework 程序集,其中 regexinfos 数组中定义的每个正则表达式由类表示。 通常,CompileToAssembly(RegexCompilationInfo[], AssemblyName, CustomAttributeBuilder[]) 方法是从生成已编译正则表达式程序集的单独应用程序中调用的。 程序集中包含的每个正则表达式具有以下特征:
- 它派生自 Regex 类。 
- 它分配由其相应 RegexCompilationInfo 对象的 - fullnamespace和- name参数定义的完全限定名称。
- 它具有默认的(或无参数)构造函数。 
通常,实例化和使用已编译正则表达式的代码位于独立于创建程序集的代码的程序集或应用程序中。
由于 CompileToAssembly 方法从方法调用生成 .NET Framework 程序集,而不是使用特定语言的类定义关键字(如 C# 中的 class 或 Visual Basic 中的 Class...End Class),因此不允许使用开发语言的标准属性语法将 .NET Framework 属性分配给程序集。 
              attributes 参数提供了用于定义应用于程序集的属性的替代方法。 对于要应用于程序集的每个属性,请执行以下操作:
- 创建表示要调用的属性构造函数的参数类型的 Type 对象的数组。 
- 检索表示要应用于新程序集的属性类的 Type 对象。 
- 调用属性 Type 对象的 GetConstructor 方法,以检索表示要调用的属性构造函数的 ConstructorInfo 对象。 将 GetConstructor 方法传递给表示构造函数参数类型的 Type 对象的数组。 
- 创建一个 Object 数组,该数组定义要传递给特性构造函数的参数。 
- 通过将构造函数传递给步骤 3 中检索的 ConstructorInfo 对象以及步骤 4 中创建的 Object 数组来实例化 CustomAttributeBuilder 对象。 
然后,可以将这些 CustomAttributeBuilder 对象的数组而不是 attributes 参数传递给 Regex.CompileToAssembly(RegexCompilationInfo[], AssemblyName, CustomAttributeBuilder[]) 方法。
调用方说明
如果要在安装了 .NET Framework 4.5 或其点版本的系统上进行开发,则以 .NET Framework 4 为目标,并使用 CompileToAssembly(RegexCompilationInfo[], AssemblyName) 方法创建包含已编译正则表达式的程序集。 尝试在该程序集中使用具有 .NET Framework 4 的系统上的正则表达式之一会引发异常。 若要解决此问题,可以执行以下操作之一:
- 在安装了 .NET Framework 4 而不是更高版本的系统上生成包含已编译正则表达式的程序集。 
- 实例化 Regex 对象或调用正则表达式模式匹配方法时,使用静态或实例 Regex 方法与 Compiled 选项,而不是从程序集调用 CompileToAssembly(RegexCompilationInfo[], AssemblyName) 和检索编译的正则表达式。