Regex.CompileToAssembly 方法

定義

編譯規則運算式並將它們以單一組件 (Assembly) 儲存至磁碟。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 5+ 與 .NET Core:不支援為編譯的規則運算式建立其組件。.NET 5+ and .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 5+ 與 .NET Core:不支援為編譯的規則運算式建立其組件。.NET 5+ and .NET Core only: Creating an assembly of compiled regular expressions is not supported.

範例

下列範例會建立名為 RegexLib.dll 的元件,並將 AssemblyTitleAttribute 屬性套用至該元件。The 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 使用反映公用程式(例如 ILDasm)來檢查資訊清單,以確認屬性已套用至元件。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 元件,而不是使用特定語言的類別定義關鍵字 (例如 class 在 c # 中 Class ,或 Visual Basic) 中的 ... End Class ,所以不允許使用開發語言的標準屬性語法將 .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將表示函式之參數類型的物件陣列傳遞給方法 TypePass 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 5+ 與 .NET Core:不支援為編譯的規則運算式建立其組件。.NET 5+ and .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 元件,而不是使用特定語言的類別定義關鍵字 (例如 class 在 c # 中 Class ,或 Visual Basic) 中的 ... End Class ,所以不允許使用開發語言的標準屬性語法將 .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.

另請參閱

適用於