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

參數

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 的元件。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 的參考 (第一個範例所建立的元件), 才會加入至專案。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.

備註

方法會產生一個 .NET Framework 元件, 其中regexinfos陣列中定義的每個正則運算式都會以類別表示。 CompileToAssembly(RegexCompilationInfo[], AssemblyName)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其對應RegexCompilationInfo物件的和name參數所定義。It 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安裝或其點發行版的系統上進行開發, 則會以為目標CompileToAssembly(RegexCompilationInfo[], AssemblyName) .NET Framework 4.NET Framework 4, 而且您會使用方法來建立包含已編譯之正則運算式的元件。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 4擲回例外狀況的系統上, 使用該元件中的其中一個正則運算式。Trying 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 現化Regex物件或呼叫正則運算式時, 請使用靜態或實例方法搭配選項,而不是從元件呼叫和抓取已編譯的正則運算式。Compiled模式比對方法。- 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);
static member CompileToAssembly : System.Text.RegularExpressions.RegexCompilationInfo[] * System.Reflection.AssemblyName * System.Reflection.Emit.CustomAttributeBuilder[] -> unit

參數

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 的元件, 並將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 的參考 (第一個範例所建立的元件), 才會加入至專案。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.

備註

方法會產生一個 .NET Framework 元件, 其中regexinfos陣列中定義的每個正則運算式都會以類別表示。 CompileToAssembly(RegexCompilationInfo[], AssemblyName, CustomAttributeBuilder[])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其對應RegexCompilationInfo物件的和name參數所定義。It 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 元件, 而不是使用特定語言的類別定義關鍵字 ( class例如在ClassC# CompileToAssemblyEnd ClassBecause 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 ClassEnd Class 在 Visual Basic) 中, 它不允許使用開發語言的標準屬性語法, 將 .NET Framework 屬性指派給元件。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物件的陣列, 代表您想要呼叫的屬性 (attribute) 的參數類型。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. 呼叫 attribute Type物件的ConstructorInfo方法, 以抓取代表您要呼叫之屬性 (attribute) 的物件。 GetConstructorCall the GetConstructor method of the attribute Type object to retrieve a ConstructorInfo object representing the attribute constructor that you want to call. 將物件Type的陣列 (代表此函式的參數類型) 傳遞給方法。GetConstructorPass 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. 藉由將ConstructorInfo在步驟3中抓取的物件和步驟4中建立Object的陣列傳遞給物件, 以具現化物件。CustomAttributeBuilderInstantiate a CustomAttributeBuilder object by passing its constructor the ConstructorInfo object retrieved in step 3 and the Object array created in step 4.

然後, 您可以將這些CustomAttributeBuilder物件的陣列 (而不是attributes參數) Regex.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安裝或其點發行版的系統上進行開發, 則會以為目標CompileToAssembly(RegexCompilationInfo[], AssemblyName) .NET Framework 4.NET Framework 4, 而且您會使用方法來建立包含已編譯之正則運算式的元件。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 4擲回例外狀況的系統上, 使用該元件中的其中一個正則運算式。Trying 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 現化Regex物件或呼叫正則運算式時, 請使用靜態或實例方法搭配選項,而不是從元件呼叫和抓取已編譯的正則運算式。Compiled模式比對方法。- 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);
static member CompileToAssembly : System.Text.RegularExpressions.RegexCompilationInfo[] * System.Reflection.AssemblyName * System.Reflection.Emit.CustomAttributeBuilder[] * string -> unit

參數

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.

備註

[], AssemblyName, CustomAttributeBuilder<x: system.text.regularexpressions.RegEx>. system.text.regularexpressions.RegEx.compiletoassembly% 28system.string 29>。 system.text.regularexpressions.RegEx>% 5b% 5d% RegexCompilationInfo。% 5b% 5d% 2csystem.string。 String% 29 > 方法會產生一個 .NET Framework 元件, 其中regexinfos陣列中所定義的每個正則運算式都是由類別所表示。The [], AssemblyName, CustomAttributeBuilder<xref:System.Text.RegularExpressions.Regex.CompileToAssembly%28System.Text.RegularExpressions.RegexCompilationInfo%5B%5D%2CSystem.Reflection.AssemblyName%2CSystem.Reflection.Emit.CustomAttributeBuilder%5B%5D%2CSystem.String%29> method generates a .NET Framework assembly in which each regular expression defined in the regexinfos array is represented by a class. 通常是 [], AssemblyName, CustomAttributeBuilder<x: system.text.regularexpressions.RegEx>. system.text.regularexpressions.RegEx.compiletoassembly% 28system.string 29>。 system.text.regularexpressions.RegEx>% 5b% 5d% RegexCompilationInfo. AssemblyName% 2csystem.string.% 5b% 5d% 2csystem.string. String% 29 > 方法是從產生編譯正則運算式之元件的個別應用程式中呼叫。Typically, the [], AssemblyName, CustomAttributeBuilder<xref:System.Text.RegularExpressions.Regex.CompileToAssembly%28System.Text.RegularExpressions.RegexCompilationInfo%5B%5D%2CSystem.Reflection.AssemblyName%2CSystem.Reflection.Emit.CustomAttributeBuilder%5B%5D%2CSystem.String%29> 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其對應RegexCompilationInfo物件的和name參數所定義。It 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 元件, 而不是使用特定語言的類別定義關鍵字 ( class例如在ClassC# CompileToAssemblyEnd ClassBecause 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 ClassEnd Class 在 Visual Basic) 中, 它不允許使用開發語言的標準屬性語法, 將 .NET Framework 屬性指派給元件。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物件的陣列, 代表您想要呼叫的屬性 (attribute) 的參數類型。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. 呼叫 attribute Type物件的ConstructorInfo方法, 以抓取代表您要呼叫之屬性 (attribute) 的物件。 GetConstructorCall the GetConstructor method of the attribute Type object to retrieve a ConstructorInfo object representing the attribute constructor that you want to call. 將代表此函式之Type參數類型的物件陣列傳遞給方法GetConstructorPass 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. 藉由將ConstructorInfo在步驟3中抓取的物件和步驟4中建立Object的陣列傳遞給物件, 以具現化物件。CustomAttributeBuilderInstantiate a CustomAttributeBuilder object by passing its constructor the ConstructorInfo object retrieved in step 3 and the Object array created in step 4.

接著, 您可以將CustomAttributeBuilder這些物件的陣列 (而不是attributes參數) 傳遞]至 [, AssemblyName<, CustomAttributeBuilder x: system.text.regularexpressions.RegEx>. system.text.regularexpressions.RegEx.compiletoassembly% 28system.string 29>。 system.text.regularexpressions.RegEx>% 5b% 5d% RegexCompilationInfo.% 5b% 5d% 2csystem.string.% 5b% 2csystem.string. CustomAttributeBuilder% 5b% 5d% 2csystem.string. String% 29 > 方法。You can then pass an array of these CustomAttributeBuilder objects instead of the attributes parameter to the [], AssemblyName, CustomAttributeBuilder<xref:System.Text.RegularExpressions.Regex.CompileToAssembly%28System.Text.RegularExpressions.RegexCompilationInfo%5B%5D%2CSystem.Reflection.AssemblyName%2CSystem.Reflection.Emit.CustomAttributeBuilder%5B%5D%2CSystem.String%29> method.

給呼叫者的注意事項

如果您是在已.NET Framework 4.5.NET Framework 4.5安裝或其點發行版的系統上進行開發, 則會以為目標CompileToAssembly(RegexCompilationInfo[], AssemblyName) .NET Framework 4.NET Framework 4, 而且您會使用方法來建立包含已編譯之正則運算式的元件。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 4擲回例外狀況的系統上, 使用該元件中的其中一個正則運算式。Trying 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 現化Regex物件或呼叫正則運算式時, 請使用靜態或實例方法搭配選項,而不是從元件呼叫和抓取已編譯的正則運算式。Compiled模式比對方法。- 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.

另請參閱

適用於