String.IsInterned(String) String.IsInterned(String) String.IsInterned(String) String.IsInterned(String) Method

Definición

Recupera una referencia a un objeto String especificado.Retrieves a reference to a specified String.

public:
 static System::String ^ IsInterned(System::String ^ str);
public static string IsInterned (string str);
static member IsInterned : string -> string
Public Shared Function IsInterned (str As String) As String

Parámetros

str
String String String String

Cadena que se va a buscar en el grupo de internos.The string to search for in the intern pool.

Devoluciones

Una referencia a str si está en el grupo de internos de Common Language Runtime; de lo contrario, null.A reference to str if it is in the common language runtime intern pool; otherwise, null.

Excepciones

Ejemplos

El ejemplo siguiente se muestra que las cadenas literales se aplica el método Intern automáticamente por el compilador.The following example demonstrates that literal strings are interned automatically by the compiler.

// Sample for String::IsInterned(String)
using namespace System;
using namespace System::Text;
using namespace System::Runtime::CompilerServices;

// In the .NET Framework 2.0 the following attribute declaration allows you to 
// avoid the use of the interning when you use NGEN.exe to compile an assembly 
// to the native image cache.
[assembly:CompilationRelaxations(CompilationRelaxations::NoStringInterning)];
void Test( int sequence, String^ str )
{
   Console::Write( "{0} The string '", sequence );
   String^ strInterned = String::IsInterned( str );
   if ( strInterned == nullptr )
      Console::WriteLine( "{0}' is not interned.", str );
   else
      Console::WriteLine( "{0}' is interned.", strInterned );
}

int main()
{
   
   // String str1 is known at compile time, and is automatically interned.
   String^ str1 = "abcd";
   
   // Constructed string, str2, is not explicitly or automatically interned.
   String^ str2 = (gcnew StringBuilder)->Append( "wx" )->Append( "yz" )->ToString();
   Console::WriteLine();
   Test( 1, str1 );
   Test( 2, str2 );
}

//This example produces the following results:

//1) The string, 'abcd', is interned.
//2) The string, 'wxyz', is not interned.

//If you use NGEN.exe to compile the assembly to the native image cache, this
//example produces the following results:

//1) The string, 'abcd', is not interned.
//2) The string, 'wxyz', is not interned.

// Sample for String.IsInterned(String)
using System;
using System.Text;
using System.Runtime.CompilerServices;

// In the .NET Framework 2.0 the following attribute declaration allows you to 
// avoid the use of the interning when you use NGEN.exe to compile an assembly 
// to the native image cache.
[assembly: CompilationRelaxations(CompilationRelaxations.NoStringInterning)]
class Sample
{
    public static void Main()
    {
        // String str1 is known at compile time, and is automatically interned.
        String str1 = "abcd";

        // Constructed string, str2, is not explicitly or automatically interned.
        String str2 = new StringBuilder().Append("wx").Append("yz").ToString();
        Console.WriteLine();
        Test(1, str1);
        Test(2, str2);
    }

    public static void Test(int sequence, String str)
    {
        Console.Write("{0}) The string, '", sequence);
        String strInterned = String.IsInterned(str);
        if (strInterned == null)
            Console.WriteLine("{0}', is not interned.", str);
        else
            Console.WriteLine("{0}', is interned.", strInterned);
    }
}

//This example produces the following results:

//1) The string, 'abcd', is interned.
//2) The string, 'wxyz', is not interned.

//If you use NGEN.exe to compile the assembly to the native image cache, this
//example produces the following results:

//1) The string, 'abcd', is not interned.
//2) The string, 'wxyz', is not interned.

' Sample for String.IsInterned(String)
Imports System
Imports System.Text
Imports System.Runtime.CompilerServices

' In the .NET Framework 2.0 the following attribute declaration allows you to 
' avoid the use of the interning when you use NGEN.exe to compile an assembly 
' to the native image cache.
<Assembly: CompilationRelaxations(CompilationRelaxations.NoStringInterning)> 
Class Sample
    Public Shared Sub Main()
        ' String str1 is known at compile time, and is automatically interned.
        Dim str1 As [String] = "abcd"

        ' Constructed string, str2, is not explicitly or automatically interned.
        Dim str2 As [String] = New StringBuilder().Append("wx").Append("yz").ToString()
        Console.WriteLine()
        Test(1, str1)
        Test(2, str2)
    End Sub 'Main

    Public Shared Sub Test(ByVal sequence As Integer, ByVal str As [String])
        Console.Write("{0}) The string, '", sequence)
        Dim strInterned As [String] = [String].IsInterned(str)
        If strInterned Is Nothing Then
            Console.WriteLine("{0}', is not interned.", str)
        Else
            Console.WriteLine("{0}', is interned.", strInterned)
        End If
    End Sub 'Test
End Class 'Sample '

'This example produces the following results:

'1) The string, 'abcd', is interned.
'2) The string, 'wxyz', is not interned.

'If you use NGEN.exe to compile the assembly to the native image cache, this
'example produces the following results:

'1) The string, 'abcd', is not interned.
'2) The string, 'wxyz', is not interned.

Comentarios

Common language runtime mantiene automáticamente una tabla, denominada el grupo de internos, que contiene una sola instancia de cada constante de cadena literal única, declarada en un programa, así como cualquier instancia única de String agregar mediante programación llamando el Intern método.The common language runtime automatically maintains a table, called the intern pool, which contains a single instance of each unique literal string constant declared in a program, as well as any unique instance of String you add programmatically by calling the Intern method.

El grupo de internos conserva el almacenamiento de la cadena.The intern pool conserves string storage. Si asigna una constante de cadena literal a varias variables, cada variable se establece para hacer referencia a la misma constante en el grupo de internos en lugar de hacer referencia a varias instancias diferentes de String que tienen valores idénticos.If you assign a literal string constant to several variables, each variable is set to reference the same constant in the intern pool instead of referencing several different instances of String that have identical values.

Este método busca un str en el grupo de internos.This method looks up str in the intern pool. Si str ya ha sido Intern, es una referencia a la instancia devuelta; de lo contrario, null se devuelve.If str has already been interned, a reference to that instance is returned; otherwise, null is returned.

Compare este método con el Intern método.Compare this method to the Intern method.

Este método no devuelve un valor booleano.This method does not return a Boolean value. Si llama al método porque desea que un valor booleano que indica si una cadena concreta se aplica el método Intern, puede usar código como el siguiente.If you call the method because you want a Boolean value that indicates whether a particular string is interned, you can use code such as the following.

using System;

public class Example
{
   public static void Main()
   {
      string str1 = "a";
      string str2 = str1 + "b";
      string str3 = str2 + "c";
      string[] strings = { "value", "part1" + "_" + "part2", str3, 
                           String.Empty, null };
      foreach (var value in strings) {
         if (value == null) continue;
         
         bool interned = String.IsInterned(value) != null;
         if (interned)
            Console.WriteLine("'{0}' is in the string intern pool.", 
                              value);
         else
            Console.WriteLine("'{0}' is not in the string intern pool.",
                              value);                      
      }
   }
}
// The example displays the following output:
//       'value' is in the string intern pool.
//       'part1_part2' is in the string intern pool.
//       'abc' is not in the string intern pool.
//       '' is in the string intern pool.
Module Example
   Public Sub Main()
      Dim str1 As String = "a"
      Dim str2 As String = str1 + "b"
      Dim str3 As String = str2 + "c"
      Dim strings() As String = { "value", "part1" + "_" + "part2", str3, 
                                  String.Empty, Nothing }
      For Each value In strings
         If value Is Nothing Then Continue For
         
         Dim interned As Boolean = (String.IsInterned(value) IsNot Nothing)
         If interned Then
            Console.WriteLine("'{0}' is in the string intern pool.", 
                              value)
         Else
            Console.WriteLine("'{0}' is not in the string intern pool.",
                              value)                      
         End If
      Next
   End Sub
End Module
' The example displays the following output:
'       'value' is in the string intern pool.
'       'part1_part2' is in the string intern pool.
'       'abc' is not in the string intern pool.
'       '' is in the string intern pool.

Nota

A partir de la versión 2.0 de .NET Framework, puede reemplazar el uso del grupo de internos cuando se usa el Ngen.exe (Native Image Generator) para instalar un ensamblado en la caché de imágenes nativas en un equipo local.Starting with the .NET Framework version 2.0, you can override the use of the intern pool when you use the Ngen.exe (Native Image Generator) to install an assembly to the native image cache on a local computer. Para obtener más información, consulte las consideraciones de rendimiento en la sección Comentarios para el Intern propiedad.For more information, see Performance Considerations in the Remarks section for the Intern property.

Se aplica a

Consulte también: