Regex.CompileToAssembly Metoda

Definicja

Kompiluje wyrażenia regularne i zapisuje je na dysku w jednym zestawie.

Przeciążenia

CompileToAssembly(RegexCompilationInfo[], AssemblyName)
Nieaktualne.

Kompiluje jeden lub więcej określonych Regex obiektów do nazwanego zestawu.

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

Kompiluje co najmniej jeden określony Regex obiekt do nazwanego zestawu z określonymi atrybutami.

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

Kompiluje co najmniej jeden określony Regex obiekt i określony plik zasobów do nazwanego zestawu z określonymi atrybutami.

Uwagi

Uwaga

Na platformach .NET Core i .NET 5 lub nowszych wywołania Regex.CompileToAssembly metody zgłaszają wyjątek PlatformNotSupportedException. Zapisywanie zestawu nie jest obsługiwane.

CompileToAssembly(RegexCompilationInfo[], AssemblyName)

Przestroga

Regex.CompileToAssembly is obsolete and not supported. Use the RegexGeneratorAttribute with the regular expression source generator instead.

Kompiluje jeden lub więcej określonych Regex obiektów do nazwanego zestawu.

public:
 static void CompileToAssembly(cli::array <System::Text::RegularExpressions::RegexCompilationInfo ^> ^ regexinfos, System::Reflection::AssemblyName ^ assemblyname);
public static void CompileToAssembly (System.Text.RegularExpressions.RegexCompilationInfo[] regexinfos, System.Reflection.AssemblyName assemblyname);
[System.Obsolete("Regex.CompileToAssembly is obsolete and not supported. Use the RegexGeneratorAttribute with the regular expression source generator instead.", DiagnosticId="SYSLIB0036", UrlFormat="https://aka.ms/dotnet-warnings/{0}")]
public static void CompileToAssembly (System.Text.RegularExpressions.RegexCompilationInfo[] regexinfos, System.Reflection.AssemblyName assemblyname);
static member CompileToAssembly : System.Text.RegularExpressions.RegexCompilationInfo[] * System.Reflection.AssemblyName -> unit
[<System.Obsolete("Regex.CompileToAssembly is obsolete and not supported. Use the RegexGeneratorAttribute with the regular expression source generator instead.", DiagnosticId="SYSLIB0036", UrlFormat="https://aka.ms/dotnet-warnings/{0}")>]
static member CompileToAssembly : System.Text.RegularExpressions.RegexCompilationInfo[] * System.Reflection.AssemblyName -> unit
Public Shared Sub CompileToAssembly (regexinfos As RegexCompilationInfo(), assemblyname As AssemblyName)

Parametry

regexinfos
RegexCompilationInfo[]

Tablica opisując wyrażenia regularne do skompilowania.

assemblyname
AssemblyName

Nazwa pliku zestawu.

Atrybuty

Wyjątki

Wartość assemblyname właściwości parametru Name jest ciągiem pustym lub null.

-lub- Wzorzec wyrażenia regularnego jednego lub większej liczby obiektów w programie regexinfos zawiera nieprawidłową składnię.

assemblyname lub regexinfos ma wartość null.

Tylko platformy .NET Core i .NET 5+: tworzenie zestawu skompilowanych wyrażeń regularnych nie jest obsługiwane.

Przykłady

Poniższy przykład tworzy zestaw o nazwie RegexLib.dll. Zestaw zawiera dwa skompilowane wyrażenia regularne. Pierwszy element , Utilities.RegularExpressions.DuplicatedStringpasuje do dwóch identycznych ciągłych wyrazów. Drugi element sprawdza, Utilities.RegularExpressions.EmailAddressczy ciąg ma poprawny format, aby był adresem e-mail.

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

Wyrażenie regularne, które sprawdza ciąg pod kątem zduplikowanych wyrazów, jest następnie tworzone i używane w poniższym przykładzie.

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.'

Pomyślna kompilacja tego drugiego przykładu wymaga odwołania do RegexLib.dll (zestawu utworzonego przez pierwszy przykład) do dodania do projektu.

Uwagi

Metoda CompileToAssembly(RegexCompilationInfo[], AssemblyName) generuje zestaw .NET Framework, w którym każde wyrażenie regularne zdefiniowane w regexinfos tablicy jest reprezentowane przez klasę. Zazwyczaj metoda jest wywoływana CompileToAssembly(RegexCompilationInfo[], AssemblyName) z oddzielnej aplikacji, która generuje zestaw skompilowanych wyrażeń regularnych. Każde wyrażenie regularne zawarte w zestawie ma następujące cechy:

  • Pochodzi on z Regex klasy .

  • Jest ona przypisana w pełni kwalifikowana nazwa zdefiniowana przez fullnamespace parametry i name odpowiadającego RegexCompilationInfo mu obiektu .

  • Ma on domyślny (lub bez parametrów) konstruktor.

Zwykle kod, który tworzy wystąpienie i używa skompilowanego wyrażenia regularnego, znajduje się w zestawie lub aplikacji, która jest oddzielona od kodu, który tworzy zestaw.

Uwagi dotyczące wywoływania

Jeśli programujesz w systemie, który ma zainstalowane wersje .NET Framework 4.5 lub jego punktów, należy użyć .NET Framework 4 i użyć CompileToAssembly(RegexCompilationInfo[], AssemblyName) metody do utworzenia zestawu zawierającego skompilowane wyrażenia regularne. Próba użycia jednego z wyrażeń regularnych w tym zestawie w systemie, który ma .NET Framework 4 zgłasza wyjątek. Aby obejść ten problem, możesz wykonać jedną z następujących czynności: — Skompiluj zestaw zawierający skompilowane wyrażenia regularne w systemie, który ma zainstalowane .NET Framework 4 zamiast nowszych wersji.

— Zamiast wywoływać CompileToAssembly(RegexCompilationInfo[], AssemblyName) i pobierać skompilowane wyrażenie regularne z zestawu, użyj metod statycznych lub wystąpień Regex z opcją Compiled podczas tworzenia wystąpienia Regex obiektu lub wywoływania metody dopasowania wzorca wyrażenia regularnego.

Zobacz też

Dotyczy

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

Przestroga

Regex.CompileToAssembly is obsolete and not supported. Use the RegexGeneratorAttribute with the regular expression source generator instead.

Kompiluje co najmniej jeden określony Regex obiekt do nazwanego zestawu z określonymi atrybutami.

public:
 static void CompileToAssembly(cli::array <System::Text::RegularExpressions::RegexCompilationInfo ^> ^ regexinfos, System::Reflection::AssemblyName ^ assemblyname, cli::array <System::Reflection::Emit::CustomAttributeBuilder ^> ^ attributes);
public static void CompileToAssembly (System.Text.RegularExpressions.RegexCompilationInfo[] regexinfos, System.Reflection.AssemblyName assemblyname, System.Reflection.Emit.CustomAttributeBuilder[]? attributes);
[System.Obsolete("Regex.CompileToAssembly is obsolete and not supported. Use the RegexGeneratorAttribute with the regular expression source generator instead.", DiagnosticId="SYSLIB0036", UrlFormat="https://aka.ms/dotnet-warnings/{0}")]
public static void CompileToAssembly (System.Text.RegularExpressions.RegexCompilationInfo[] regexinfos, System.Reflection.AssemblyName assemblyname, System.Reflection.Emit.CustomAttributeBuilder[]? attributes);
public static void CompileToAssembly (System.Text.RegularExpressions.RegexCompilationInfo[] regexinfos, System.Reflection.AssemblyName assemblyname, System.Reflection.Emit.CustomAttributeBuilder[] attributes);
static member CompileToAssembly : System.Text.RegularExpressions.RegexCompilationInfo[] * System.Reflection.AssemblyName * System.Reflection.Emit.CustomAttributeBuilder[] -> unit
[<System.Obsolete("Regex.CompileToAssembly is obsolete and not supported. Use the RegexGeneratorAttribute with the regular expression source generator instead.", DiagnosticId="SYSLIB0036", UrlFormat="https://aka.ms/dotnet-warnings/{0}")>]
static member CompileToAssembly : System.Text.RegularExpressions.RegexCompilationInfo[] * System.Reflection.AssemblyName * System.Reflection.Emit.CustomAttributeBuilder[] -> unit
Public Shared Sub CompileToAssembly (regexinfos As RegexCompilationInfo(), assemblyname As AssemblyName, attributes As CustomAttributeBuilder())

Parametry

regexinfos
RegexCompilationInfo[]

Tablica opisując wyrażenia regularne do skompilowania.

assemblyname
AssemblyName

Nazwa pliku zestawu.

attributes
CustomAttributeBuilder[]

Tablica, która definiuje atrybuty, które mają być stosowane do zestawu.

Atrybuty

Wyjątki

Wartość assemblyname właściwości parametru Name jest ciągiem pustym lub null.

-lub- Wzorzec wyrażenia regularnego jednego lub większej liczby obiektów w programie regexinfos zawiera nieprawidłową składnię.

assemblyname lub regexinfos ma wartość null.

Tylko platformy .NET Core i .NET 5+: tworzenie zestawu skompilowanych wyrażeń regularnych nie jest obsługiwane.

Przykłady

Poniższy przykład tworzy zestaw o nazwie RegexLib.dll i stosuje AssemblyTitleAttribute do niego atrybut . Zestaw zawiera dwa skompilowane wyrażenia regularne. Pierwszy element , Utilities.RegularExpressions.DuplicatedStringpasuje do dwóch identycznych ciągłych wyrazów. Drugi element sprawdza, Utilities.RegularExpressions.EmailAddressczy ciąg ma poprawny format, aby był adresem e-mail.

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

Możesz sprawdzić, czy AssemblyTitleAttribute atrybut został zastosowany do zestawu, sprawdzając jego manifest za pomocą narzędzia odbicia, takiego jak ILDasm.

Wyrażenie regularne, które sprawdza ciąg pod kątem zduplikowanych wyrazów, jest następnie tworzone i używane w poniższym przykładzie.

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.'

Pomyślna kompilacja tego drugiego przykładu wymaga odwołania do RegexLib.dll (zestawu utworzonego przez pierwszy przykład) do dodania do projektu.

Uwagi

Metoda CompileToAssembly(RegexCompilationInfo[], AssemblyName, CustomAttributeBuilder[]) generuje zestaw .NET Framework, w którym każde wyrażenie regularne zdefiniowane w regexinfos tablicy jest reprezentowane przez klasę. Zazwyczaj metoda jest wywoływana CompileToAssembly(RegexCompilationInfo[], AssemblyName, CustomAttributeBuilder[]) z oddzielnej aplikacji, która generuje zestaw skompilowanych wyrażeń regularnych. Każde wyrażenie regularne zawarte w zestawie ma następujące cechy:

  • Pochodzi on z Regex klasy .

  • Jest ona przypisana w pełni kwalifikowana nazwa zdefiniowana przez fullnamespace parametry i name odpowiadającego RegexCompilationInfo mu obiektu .

  • Ma on domyślny (lub bez parametrów) konstruktor.

Zwykle kod, który tworzy wystąpienie i używa skompilowanego wyrażenia regularnego, znajduje się w zestawie lub aplikacji, która jest oddzielona od kodu, który tworzy zestaw.

CompileToAssembly Ponieważ metoda generuje zestaw .NET Framework z wywołania metody zamiast używać słowa kluczowego definicji klasy określonego języka (na przykład class w języku C# lub Class...End Class w Visual Basic), nie zezwala .NET Framework atrybutów do przypisania do zestawu przy użyciu standardowej składni atrybutów języka programowania. Parametr attributes udostępnia alternatywną metodę definiowania atrybutów, które mają zastosowanie do zestawu. Dla każdego atrybutu, który chcesz zastosować do zestawu, wykonaj następujące czynności:

  1. Utwórz tablicę Type obiektów reprezentujących typy parametrów konstruktora atrybutu, który chcesz wywołać.

  2. Pobierz obiekt reprezentujący klasę Type atrybutów, która ma zostać zastosowana do nowego zestawu.

  3. Wywołaj metodę GetConstructor obiektu atrybutu Type , aby pobrać ConstructorInfo obiekt reprezentujący konstruktor atrybutu, który chcesz wywołać. Przekaż metodę GetConstructor tablicy Type obiektów reprezentujących typy parametrów konstruktora.

  4. Utwórz tablicę Object , która definiuje parametry do przekazania do konstruktora atrybutu.

  5. CustomAttributeBuilder Utworzenie wystąpienia obiektu przez przekazanie jego konstruktora obiektu pobranego ConstructorInfo w kroku 3 i tablicy utworzonej Object w kroku 4.

Następnie można przekazać tablicę tych CustomAttributeBuilder obiektów zamiast parametru attributes Regex.CompileToAssembly(RegexCompilationInfo[], AssemblyName, CustomAttributeBuilder[]) do metody .

Uwagi dotyczące wywoływania

Jeśli programujesz w systemie, który ma zainstalowane wersje .NET Framework 4.5 lub jego punktów, należy użyć .NET Framework 4 i użyć CompileToAssembly(RegexCompilationInfo[], AssemblyName) metody do utworzenia zestawu zawierającego skompilowane wyrażenia regularne. Próba użycia jednego z wyrażeń regularnych w tym zestawie w systemie, który ma .NET Framework 4 zgłasza wyjątek. Aby obejść ten problem, możesz wykonać jedną z następujących czynności: — Skompiluj zestaw zawierający skompilowane wyrażenia regularne w systemie, który ma zainstalowany .NET Framework 4 zamiast nowszych wersji.

— Zamiast wywoływać CompileToAssembly(RegexCompilationInfo[], AssemblyName) i pobierać skompilowane wyrażenie regularne z zestawu, użyj metod statycznych lub wystąpień z Compiled opcją podczas tworzenia wystąpienia Regex obiektu lub wywoływania Regex metody dopasowywania wzorca wyrażenia regularnego.

Zobacz też

Dotyczy

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

Przestroga

Regex.CompileToAssembly is obsolete and not supported. Use the RegexGeneratorAttribute with the regular expression source generator instead.

Kompiluje co najmniej jeden określony Regex obiekt i określony plik zasobów do nazwanego zestawu z określonymi atrybutami.

public:
 static void CompileToAssembly(cli::array <System::Text::RegularExpressions::RegexCompilationInfo ^> ^ regexinfos, System::Reflection::AssemblyName ^ assemblyname, cli::array <System::Reflection::Emit::CustomAttributeBuilder ^> ^ attributes, System::String ^ resourceFile);
public static void CompileToAssembly (System.Text.RegularExpressions.RegexCompilationInfo[] regexinfos, System.Reflection.AssemblyName assemblyname, System.Reflection.Emit.CustomAttributeBuilder[]? attributes, string? resourceFile);
[System.Obsolete("Regex.CompileToAssembly is obsolete and not supported. Use the RegexGeneratorAttribute with the regular expression source generator instead.", DiagnosticId="SYSLIB0036", UrlFormat="https://aka.ms/dotnet-warnings/{0}")]
public static void CompileToAssembly (System.Text.RegularExpressions.RegexCompilationInfo[] regexinfos, System.Reflection.AssemblyName assemblyname, System.Reflection.Emit.CustomAttributeBuilder[]? attributes, string? resourceFile);
public static void CompileToAssembly (System.Text.RegularExpressions.RegexCompilationInfo[] regexinfos, System.Reflection.AssemblyName assemblyname, System.Reflection.Emit.CustomAttributeBuilder[] attributes, string resourceFile);
static member CompileToAssembly : System.Text.RegularExpressions.RegexCompilationInfo[] * System.Reflection.AssemblyName * System.Reflection.Emit.CustomAttributeBuilder[] * string -> unit
[<System.Obsolete("Regex.CompileToAssembly is obsolete and not supported. Use the RegexGeneratorAttribute with the regular expression source generator instead.", DiagnosticId="SYSLIB0036", UrlFormat="https://aka.ms/dotnet-warnings/{0}")>]
static member CompileToAssembly : System.Text.RegularExpressions.RegexCompilationInfo[] * System.Reflection.AssemblyName * System.Reflection.Emit.CustomAttributeBuilder[] * string -> unit
Public Shared Sub CompileToAssembly (regexinfos As RegexCompilationInfo(), assemblyname As AssemblyName, attributes As CustomAttributeBuilder(), resourceFile As String)

Parametry

regexinfos
RegexCompilationInfo[]

Tablica opisując wyrażenia regularne do skompilowania.

assemblyname
AssemblyName

Nazwa pliku zestawu.

attributes
CustomAttributeBuilder[]

Tablica, która definiuje atrybuty, które mają być stosowane do zestawu.

resourceFile
String

Nazwa pliku zasobu Win32 do uwzględnienia w zestawie.

Atrybuty

Wyjątki

Wartość assemblyname właściwości parametru Name jest pustym lub null ciągiem.

-lub- Wzorzec wyrażenia regularnego jednego lub większej liczby obiektów w programie regexinfos zawiera nieprawidłową składnię.

assemblyname lub regexinfos to null.

Parametr resourceFile wyznacza nieprawidłowy plik zasobu Win32.

Nie można odnaleźć pliku wyznaczonego resourceFile przez parametr .

Tylko platformy .NET Core i .NET 5+: tworzenie zestawu skompilowanych wyrażeń regularnych nie jest obsługiwane.

Uwagi

Metoda CompileToAssembly(RegexCompilationInfo[], AssemblyName, CustomAttributeBuilder[], String) generuje zestaw .NET Framework, w którym każde wyrażenie regularne zdefiniowane w regexinfos tablicy jest reprezentowane przez klasę. CompileToAssembly(RegexCompilationInfo[], AssemblyName, CustomAttributeBuilder[], String) Zazwyczaj metoda jest wywoływana z oddzielnej aplikacji, która generuje zestaw skompilowanych wyrażeń regularnych. Każde wyrażenie regularne zawarte w zestawie ma następujące cechy:

  • Pochodzi on z Regex klasy .

  • Jest przypisana w pełni kwalifikowana nazwa zdefiniowana przez fullnamespace parametry i name odpowiedniego RegexCompilationInfo obiektu.

  • Ma on domyślny (lub bez parametrów) konstruktor.

Zwykle kod, który tworzy wystąpienie i używa skompilowanego wyrażenia regularnego, znajduje się w zestawie lub aplikacji, która jest oddzielona od kodu, który tworzy zestaw.

CompileToAssembly Ponieważ metoda generuje zestaw .NET Framework z wywołania metody zamiast używać słowa kluczowego definicji klasy określonego języka (na przykład class w języku C# lub Class...End Class w Visual Basic), nie zezwala na przypisywanie .NET Framework atrybutów do zestawu przy użyciu standardowej składni atrybutów języka deweloperskiego. Parametr attributes udostępnia alternatywną metodę definiowania atrybutów, które mają zastosowanie do zestawu. Dla każdego atrybutu, który chcesz zastosować do zestawu, wykonaj następujące czynności:

  1. Utwórz tablicę Type obiektów reprezentujących typy parametrów konstruktora atrybutu, który chcesz wywołać.

  2. Pobierz obiekt reprezentujący klasę Type atrybutów, którą chcesz zastosować do nowego zestawu.

  3. Wywołaj metodę ConstructorInfo obiektu atrybutuType, GetConstructor aby pobrać obiekt reprezentujący konstruktor atrybutu, który chcesz wywołać. Przekaż metodę GetConstructor tablicy Type obiektów reprezentujących typy parametrów konstruktora

  4. Utwórz tablicę definiującą Object parametry, które mają zostać przekazane do konstruktora atrybutu.

  5. Utworzenie wystąpienia obiektu przez przekazanie konstruktora CustomAttributeBuilder obiektu pobranego ConstructorInfo w kroku 3 i tablicy utworzonej Object w kroku 4.

Następnie można przekazać tablicę tych CustomAttributeBuilder obiektów zamiast parametru attributes CompileToAssembly(RegexCompilationInfo[], AssemblyName, CustomAttributeBuilder[], String) do metody .

Uwagi dotyczące wywoływania

Jeśli programujesz w systemie, w którym zainstalowano .NET Framework 4.5 lub jego wydania punktów, docelową .NET Framework 4 jest CompileToAssembly(RegexCompilationInfo[], AssemblyName) używana metoda do utworzenia zestawu zawierającego skompilowane wyrażenia regularne. Próba użycia jednego z wyrażeń regularnych w tym zestawie w systemie, który ma .NET Framework 4 zgłasza wyjątek. Aby obejść ten problem, możesz wykonać jedną z następujących czynności: — Skompiluj zestaw zawierający skompilowane wyrażenia regularne w systemie, który ma zainstalowany .NET Framework 4 zamiast nowszych wersji.

— Zamiast wywoływać CompileToAssembly(RegexCompilationInfo[], AssemblyName) i pobierać skompilowane wyrażenie regularne z zestawu, użyj metod statycznych lub wystąpień z Compiled opcją podczas tworzenia wystąpienia Regex obiektu lub wywoływania Regex metody dopasowywania wzorca wyrażenia regularnego.

Zobacz też

Dotyczy