Regex.CompileToAssembly 方法

定义

编译正则表达式,并将其保存到单个程序集的磁盘中。Compiles regular expressions and saves them to disk in a single assembly.

重载

CompileToAssembly(RegexCompilationInfo[], AssemblyName)

将一个或多个指定的 Regex 对象编译为命名程序集。Compiles one or more specified Regex objects to a named assembly.

CompileToAssembly(RegexCompilationInfo[], AssemblyName, CustomAttributeBuilder[])

将一个或多个指定的 Regex 对象编译为具有指定特性的命名程序集。Compiles one or more specified Regex objects to a named assembly with the specified attributes.

CompileToAssembly(RegexCompilationInfo[], AssemblyName, CustomAttributeBuilder[], String)

将一个或多个指定的 Regex 对象和一个指定的资源文件编译为具有指定特性的命名程序集。Compiles one or more specified Regex objects and a specified resource file to a named assembly with the specified attributes.

注解

在 .NET Core 中,对方法的调用将 Regex.CompileToAssembly 引发 PlatformNotSupportedException ; 不支持写出程序集。On .NET Core, calls to the Regex.CompileToAssembly method throw a PlatformNotSupportedException; writing out an assembly is not supported.

CompileToAssembly(RegexCompilationInfo[], AssemblyName)

将一个或多个指定的 Regex 对象编译为命名程序集。Compiles one or more specified Regex objects to a named assembly.

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);
static member CompileToAssembly : System.Text.RegularExpressions.RegexCompilationInfo[] * System.Reflection.AssemblyName -> unit
Public Shared Sub CompileToAssembly (regexinfos As RegexCompilationInfo(), assemblyname As AssemblyName)

参数

regexinfos
RegexCompilationInfo[]

描述要编译的正则表达式的数组。An array that describes the regular expressions to compile.

assemblyname
AssemblyName

程序集的文件名。The file name of the assembly.

例外

assemblyname 参数的 Name 属性值是一个空字符串或 null。The value of the assemblyname parameter's Name property is an empty or null string.

- 或 --or- regexinfos 中的一个或多个对象的正则表达式模式包含无效语法。The regular expression pattern of one or more objects in regexinfos contains invalid syntax.

assemblynameregexinfosnullassemblyname or regexinfos is null.

仅 .NET Core:不支持创建已编译的正则表达式的程序集。.NET Core only: Creating an assembly of compiled regular expressions is not supported.

示例

下面的示例创建一个名为 RegexLib.dll 的程序集。The following example creates an assembly named RegexLib.dll. 程序集包括两个已编译的正则表达式。The assembly includes two compiled regular expressions. 第一个是, Utilities.RegularExpressions.DuplicatedString 匹配两个相同的连续单词。The first, Utilities.RegularExpressions.DuplicatedString, matches two identical contiguous words. 第二个 Utilities.RegularExpressions.EmailAddress 检查字符串的格式是否正确,是否为电子邮件地址。The second, Utilities.RegularExpressions.EmailAddress, checks whether a string has the correct format to be an email address.

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

然后,使用正则表达式来检查字符串中是否存在重复的单词,并将其用于以下示例。The regular expression that checks a string for duplicate words is then instantiated and used by the following example.

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 () 添加到项目中的第一个示例所创建的程序集。Successful compilation of this second example requires a reference to RegexLib.dll (the assembly created by the first example) to be added to the project.

注解

CompileToAssembly(RegexCompilationInfo[], AssemblyName)方法生成一个 .NET Framework 程序集,其中在数组中定义的每个正则表达式 regexinfos 由一个类表示。The CompileToAssembly(RegexCompilationInfo[], AssemblyName) method generates a .NET Framework assembly in which each regular expression defined in the regexinfos array is represented by a class. 通常, CompileToAssembly(RegexCompilationInfo[], AssemblyName) 方法是从生成已编译的正则表达式的程序集的单独的应用程序中调用的。Typically, the CompileToAssembly(RegexCompilationInfo[], AssemblyName) method is called from a separate application that generates an assembly of compiled regular expressions. 程序集中包含的每个正则表达式具有以下特征:Each regular expression included in the assembly has the following characteristics:

  • 它派生自 Regex 类。It is derived from the Regex class.

  • 为它分配由 fullnamespace 其对应对象的和参数定义的完全限定名称 name RegexCompilationInfoIt is assigned the fully qualified name that is defined by the fullnamespace and name parameters of its corresponding RegexCompilationInfo object.

  • 它具有默认 (或无参数) 构造函数。It has a default (or parameterless) constructor.

通常,在独立于创建程序集的代码的程序集或应用程序中,会找到实例化并使用已编译的正则表达式的代码。Ordinarily, the code that instantiates and uses the compiled regular expression is found in an assembly or application that is separate from the code that creates the assembly.

调用方说明

如果要在 .NET Framework 4.5.NET Framework 4.5 安装了或其单点版本的系统上进行开发,则需要 .NET Framework 4.NET Framework 4 以为目标,并使用 CompileToAssembly(RegexCompilationInfo[], AssemblyName) 方法创建包含已编译的正则表达式的程序集。If you are developing on a system that has .NET Framework 4.5.NET Framework 4.5 or its point releases installed, you target .NET Framework 4.NET Framework 4, and you use the CompileToAssembly(RegexCompilationInfo[], AssemblyName) method to create an assembly that contains compiled regular expressions. 尝试在已引发异常的系统上,使用该程序集中的某个正则表达式 .NET Framework 4.NET Framework 4Trying to use one of the regular expressions in that assembly on a system that has .NET Framework 4.NET Framework 4 throws an exception. 若要解决此问题,可执行下列操作之一:To work around this problem, you can do either of the following: -在 .NET Framework 4.NET Framework 4 安装了而不是更高版本的系统上生成包含已编译的正则表达式的程序集。- Build the assembly that contains the compiled regular expressions on a system that has .NET Framework 4.NET Framework 4 instead of later versions installed.

-在 CompileToAssembly(RegexCompilationInfo[], AssemblyName) Regex Compiled 实例化 Regex 对象或调用正则表达式模式匹配方法时,请使用带有选项的静态方法或实例方法,而不是从程序集调用和检索已编译的正则表达式。- Instead of calling CompileToAssembly(RegexCompilationInfo[], AssemblyName) and retrieving the compiled regular expression from an assembly, use either static or instance Regex methods with the Compiled option when you instantiate a Regex object or call a regular expression pattern matching method.

另请参阅

适用于

CompileToAssembly(RegexCompilationInfo[], AssemblyName, CustomAttributeBuilder[])

将一个或多个指定的 Regex 对象编译为具有指定特性的命名程序集。Compiles one or more specified Regex objects to a named assembly with the specified attributes.

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);
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
Public Shared Sub CompileToAssembly (regexinfos As RegexCompilationInfo(), assemblyname As AssemblyName, attributes As CustomAttributeBuilder())

参数

regexinfos
RegexCompilationInfo[]

描述要编译的正则表达式的数组。An array that describes the regular expressions to compile.

assemblyname
AssemblyName

程序集的文件名。The file name of the assembly.

attributes
CustomAttributeBuilder[]

定义要应用于程序集的特性的数组。An array that defines the attributes to apply to the assembly.

例外

assemblyname 参数的 Name 属性值是一个空字符串或 null。The value of the assemblyname parameter's Name property is an empty or null string.

- 或 --or- regexinfos 中的一个或多个对象的正则表达式模式包含无效语法。The regular expression pattern of one or more objects in regexinfos contains invalid syntax.

assemblynameregexinfosnullassemblyname or regexinfos is null.

仅 .NET Core:不支持创建已编译的正则表达式的程序集。.NET Core only: Creating an assembly of compiled regular expressions is not supported.

示例

下面的示例创建一个名为 RegexLib.dll 的程序集,并将该特性应用于该程序集 AssemblyTitleAttributeThe following example creates an assembly named RegexLib.dll and applies the AssemblyTitleAttribute attribute to it. 程序集包括两个已编译的正则表达式。The assembly includes two compiled regular expressions. 第一个是, Utilities.RegularExpressions.DuplicatedString 匹配两个相同的连续单词。The first, Utilities.RegularExpressions.DuplicatedString, matches two identical contiguous words. 第二个 Utilities.RegularExpressions.EmailAddress 检查字符串的格式是否正确,是否为电子邮件地址。The second, Utilities.RegularExpressions.EmailAddress, checks whether a string has the correct format to be an email address.

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

可以 AssemblyTitleAttribute 通过使用类型为的反射实用程序来检查程序集是否已应用于该程序集。You can verify that the AssemblyTitleAttribute attribute has been applied to the assembly by examining its manifest with a reflection utility such as ILDasm.

然后,使用正则表达式来检查字符串中是否存在重复的单词,并将其用于以下示例。The regular expression that checks a string for duplicate words is then instantiated and used by the following example.

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 () 添加到项目中的第一个示例所创建的程序集。Successful compilation of this second example requires a reference to RegexLib.dll (the assembly created by the first example) to be added to the project.

注解

CompileToAssembly(RegexCompilationInfo[], AssemblyName, CustomAttributeBuilder[])方法生成一个 .NET Framework 程序集,其中在数组中定义的每个正则表达式 regexinfos 由一个类表示。The CompileToAssembly(RegexCompilationInfo[], AssemblyName, CustomAttributeBuilder[]) method generates a .NET Framework assembly in which each regular expression defined in the regexinfos array is represented by a class. 通常, CompileToAssembly(RegexCompilationInfo[], AssemblyName, CustomAttributeBuilder[]) 方法是从生成已编译的正则表达式的程序集的单独的应用程序中调用的。Typically, the CompileToAssembly(RegexCompilationInfo[], AssemblyName, CustomAttributeBuilder[]) method is called from a separate application that generates an assembly of compiled regular expressions. 程序集中包含的每个正则表达式具有以下特征:Each regular expression included in the assembly has the following characteristics:

  • 它派生自 Regex 类。It is derived from the Regex class.

  • 为它分配由 fullnamespace 其对应对象的和参数定义的完全限定名称 name RegexCompilationInfoIt is assigned the fully qualified name that is defined by the fullnamespace and name parameters of its corresponding RegexCompilationInfo object.

  • 它具有默认 (或无参数) 构造函数。It has a default (or parameterless) constructor.

通常,在独立于创建程序集的代码的程序集或应用程序中,会找到实例化并使用已编译的正则表达式的代码。Ordinarily, the code that instantiates and uses the compiled regular expression is found in an assembly or application that is separate from the code that creates the assembly.

由于 CompileToAssembly 方法从方法调用生成 .NET Framework 程序集,而不是使用特定语言的类定义关键字,如 c # 中的 (classClass ... End Class 在 Visual Basic) 中,它不允许使用开发语言的标准特性语法将 .NET Framework 特性分配给程序集。Because the CompileToAssembly method generates a .NET Framework assembly from a method call instead of using a particular language's class definition keyword (such as class in C# or Class...End Class in Visual Basic), it does not allow .NET Framework attributes to be assigned to the assembly by using the development language's standard attribute syntax. attributes参数提供了一种替代方法,用于定义应用于程序集的特性。The attributes parameter provides an alternative method for defining the attributes that apply to the assembly. 对于要应用于程序集的每个属性,请执行以下操作:For each attribute that you want to apply to the assembly, do the following:

  1. 创建对象的数组,这些 Type 对象表示要调用的特性构造函数的参数类型。Create an array of Type objects representing the parameter types of the attribute constructor that you want to call.

  2. 检索一个 Type 对象,该对象表示要应用于新程序集的特性类。Retrieve a Type object representing the attribute class that you want to apply to the new assembly.

  3. 调用 GetConstructor attribute 对象的方法 Type 以检索一个对象,该 ConstructorInfo 对象表示要调用的特性构造函数。Call the GetConstructor method of the attribute Type object to retrieve a ConstructorInfo object representing the attribute constructor that you want to call. GetConstructor向方法传递 Type 表示构造函数的参数类型的对象数组。Pass the GetConstructor method the array of Type objects that represents the constructor's parameter types.

  4. 创建一个 Object 数组,该数组定义要传递给该特性的构造函数的参数。Create a Object array that defines the parameters to pass to the attribute's constructor.

  5. CustomAttributeBuilder通过将对象的构造函数传递给在第 ConstructorInfo 3 步中检索的对象以及 Object 在步骤4中创建的数组来实例化对象。Instantiate a CustomAttributeBuilder object by passing its constructor the ConstructorInfo object retrieved in step 3 and the Object array created in step 4.

然后,可以将这些对象的数组 CustomAttributeBuilder (而非参数)传递 attributesRegex.CompileToAssembly(RegexCompilationInfo[], AssemblyName, CustomAttributeBuilder[]) 方法。You can then pass an array of these CustomAttributeBuilder objects instead of the attributes parameter to the Regex.CompileToAssembly(RegexCompilationInfo[], AssemblyName, CustomAttributeBuilder[]) method.

调用方说明

如果要在 .NET Framework 4.5.NET Framework 4.5 安装了或其单点版本的系统上进行开发,则需要 .NET Framework 4.NET Framework 4 以为目标,并使用 CompileToAssembly(RegexCompilationInfo[], AssemblyName) 方法创建包含已编译的正则表达式的程序集。If you are developing on a system that has .NET Framework 4.5.NET Framework 4.5 or its point releases installed, you target .NET Framework 4.NET Framework 4, and you use the CompileToAssembly(RegexCompilationInfo[], AssemblyName) method to create an assembly that contains compiled regular expressions. 尝试在已引发异常的系统上,使用该程序集中的某个正则表达式 .NET Framework 4.NET Framework 4Trying to use one of the regular expressions in that assembly on a system that has .NET Framework 4.NET Framework 4 throws an exception. 若要解决此问题,可执行下列操作之一:To work around this problem, you can do either of the following: -在 .NET Framework 4.NET Framework 4 安装了而不是更高版本的系统上生成包含已编译的正则表达式的程序集。- Build the assembly that contains the compiled regular expressions on a system that has .NET Framework 4.NET Framework 4 instead of later versions installed.

-在 CompileToAssembly(RegexCompilationInfo[], AssemblyName) Regex Compiled 实例化 Regex 对象或调用正则表达式模式匹配方法时,请使用带有选项的静态方法或实例方法,而不是从程序集调用和检索已编译的正则表达式。- Instead of calling CompileToAssembly(RegexCompilationInfo[], AssemblyName) and retrieving the compiled regular expression from an assembly, use either static or instance Regex methods with the Compiled option when you instantiate a Regex object or call a regular expression pattern matching method.

另请参阅

适用于

CompileToAssembly(RegexCompilationInfo[], AssemblyName, CustomAttributeBuilder[], String)

将一个或多个指定的 Regex 对象和一个指定的资源文件编译为具有指定特性的命名程序集。Compiles one or more specified Regex objects and a specified resource file to a named assembly with the specified attributes.

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);
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
Public Shared Sub CompileToAssembly (regexinfos As RegexCompilationInfo(), assemblyname As AssemblyName, attributes As CustomAttributeBuilder(), resourceFile As String)

参数

regexinfos
RegexCompilationInfo[]

描述要编译的正则表达式的数组。An array that describes the regular expressions to compile.

assemblyname
AssemblyName

程序集的文件名。The file name of the assembly.

attributes
CustomAttributeBuilder[]

定义要应用于程序集的特性的数组。An array that defines the attributes to apply to the assembly.

resourceFile
String

要包含在程序集中的 Win32 资源文件的名称。The name of the Win32 resource file to include in the assembly.

例外

assemblyname 参数的 Name 属性值是一个空字符串或 null。The value of the assemblyname parameter's Name property is an empty or null string.

- 或 --or- regexinfos 中的一个或多个对象的正则表达式模式包含无效语法。The regular expression pattern of one or more objects in regexinfos contains invalid syntax.

assemblynameregexinfosnullassemblyname or regexinfos is null.

resourceFile 参数指定了无效的 Win32 资源文件。The resourceFile parameter designates an invalid Win32 resource file.

找不到 resourceFile 参数指定的文件。The file designated by the resourceFile parameter cannot be found.

仅 .NET Core:不支持创建已编译的正则表达式的程序集。.NET Core only: Creating an assembly of compiled regular expressions is not supported.

注解

CompileToAssembly(RegexCompilationInfo[], AssemblyName, CustomAttributeBuilder[], String)方法生成一个 .NET Framework 程序集,其中在数组中定义的每个正则表达式 regexinfos 由一个类表示。The CompileToAssembly(RegexCompilationInfo[], AssemblyName, CustomAttributeBuilder[], String) method generates a .NET Framework assembly in which each regular expression defined in the regexinfos array is represented by a class. 通常, CompileToAssembly(RegexCompilationInfo[], AssemblyName, CustomAttributeBuilder[], String) 方法是从生成已编译的正则表达式的程序集的单独的应用程序中调用的。Typically, the CompileToAssembly(RegexCompilationInfo[], AssemblyName, CustomAttributeBuilder[], String) method is called from a separate application that generates an assembly of compiled regular expressions. 程序集中包含的每个正则表达式具有以下特征:Each regular expression included in the assembly has the following characteristics:

  • 它派生自 Regex 类。It is derived from the Regex class.

  • 为它分配由 fullnamespace 其对应对象的和参数定义的完全限定名称 name RegexCompilationInfoIt is assigned the fully qualified name that is defined by the fullnamespace and name parameters of its corresponding RegexCompilationInfo object.

  • 它具有默认 (或无参数) 构造函数。It has a default (or parameterless) constructor.

通常,在独立于创建程序集的代码的程序集或应用程序中,会找到实例化并使用已编译的正则表达式的代码。Ordinarily, the code that instantiates and uses the compiled regular expression is found in an assembly or application that is separate from the code that creates the assembly.

由于 CompileToAssembly 方法从方法调用生成 .NET Framework 程序集,而不是使用特定语言的类定义关键字,如 c # 中的 (classClass ... End Class 在 Visual Basic) 中,它不允许使用开发语言的标准特性语法将 .NET Framework 特性分配给程序集。Because the CompileToAssembly method generates a .NET Framework assembly from a method call instead of using a particular language's class definition keyword (such as class in C# or Class...End Class in Visual Basic), it does not allow .NET Framework attributes to be assigned to the assembly by using the development language's standard attribute syntax. attributes参数提供了一种替代方法,用于定义应用于程序集的特性。The attributes parameter provides an alternative method for defining the attributes that apply to the assembly. 对于要应用于程序集的每个属性,请执行以下操作:For each attribute that you want to apply to the assembly, do the following:

  1. 创建对象的数组,这些 Type 对象表示要调用的特性构造函数的参数类型。Create an array of Type objects representing the parameter types of the attribute constructor that you want to call.

  2. 检索一个 Type 对象,该对象表示要应用于新程序集的特性类。Retrieve a Type object representing the attribute class that you want to apply to the new assembly.

  3. 调用 GetConstructor attribute 对象的方法 Type 以检索一个对象,该 ConstructorInfo 对象表示要调用的特性构造函数。Call the GetConstructor method of the attribute Type object to retrieve a ConstructorInfo object representing the attribute constructor that you want to call. GetConstructor向方法传递 Type 表示构造函数的参数类型的对象数组Pass the GetConstructor method the array of Type objects that represents the constructor's parameter types

  4. 创建一个 Object 数组,该数组定义要传递给该特性的构造函数的参数。Create a Object array that defines the parameters to pass to the attribute's constructor.

  5. CustomAttributeBuilder通过将对象的构造函数传递给在第 ConstructorInfo 3 步中检索的对象以及 Object 在步骤4中创建的数组来实例化对象。Instantiate a CustomAttributeBuilder object by passing its constructor the ConstructorInfo object retrieved in step 3 and the Object array created in step 4.

然后,可以将这些对象的数组 CustomAttributeBuilder (而非参数)传递 attributesCompileToAssembly(RegexCompilationInfo[], AssemblyName, CustomAttributeBuilder[], String) 方法。You can then pass an array of these CustomAttributeBuilder objects instead of the attributes parameter to the CompileToAssembly(RegexCompilationInfo[], AssemblyName, CustomAttributeBuilder[], String) method.

调用方说明

如果要在 .NET Framework 4.5.NET Framework 4.5 安装了或其单点版本的系统上进行开发,则需要 .NET Framework 4.NET Framework 4 以为目标,并使用 CompileToAssembly(RegexCompilationInfo[], AssemblyName) 方法创建包含已编译的正则表达式的程序集。If you are developing on a system that has .NET Framework 4.5.NET Framework 4.5 or its point releases installed, you target .NET Framework 4.NET Framework 4, and you use the CompileToAssembly(RegexCompilationInfo[], AssemblyName) method to create an assembly that contains compiled regular expressions. 尝试在已引发异常的系统上,使用该程序集中的某个正则表达式 .NET Framework 4.NET Framework 4Trying to use one of the regular expressions in that assembly on a system that has .NET Framework 4.NET Framework 4 throws an exception. 若要解决此问题,可执行下列操作之一:To work around this problem, you can do either of the following: -在 .NET Framework 4.NET Framework 4 安装了而不是更高版本的系统上生成包含已编译的正则表达式的程序集。- Build the assembly that contains the compiled regular expressions on a system that has .NET Framework 4.NET Framework 4 instead of later versions installed.

-在 CompileToAssembly(RegexCompilationInfo[], AssemblyName) Regex Compiled 实例化 Regex 对象或调用正则表达式模式匹配方法时,请使用带有选项的静态方法或实例方法,而不是从程序集调用和检索已编译的正则表达式。- Instead of calling CompileToAssembly(RegexCompilationInfo[], AssemblyName) and retrieving the compiled regular expression from an assembly, use either static or instance Regex methods with the Compiled option when you instantiate a Regex object or call a regular expression pattern matching method.

另请参阅

适用于