String.IsInterned(String) Método

Definição

Recupera uma referência a um String especificado.

C#
public static string? IsInterned (string str);
C#
public static string IsInterned (string str);

Parâmetros

str
String

A cadeia de caracteres para pesquisar no pool interno.

Retornos

String

Uma referência a str se ele estiver no pool interno de Common Language Runtime; caso contrário, null.

Exceções

str é null.

Exemplos

O exemplo a seguir demonstra que as cadeias de caracteres literais são estagiários automaticamente pelo compilador.

C#
// 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.

Comentários

O Common Language Runtime mantém automaticamente uma tabela, chamada de pool do estagiário, que contém uma única instância de cada constante de cadeia de caracteres literal exclusiva declarada em um programa, bem como qualquer instância exclusiva do String que você adicionar programaticamente chamando o Intern método.

O pool do estagiário conserva o armazenamento de cadeia de caracteres. Se você atribuir uma constante de cadeia de caracteres literal a várias variáveis, cada variável será definida para referenciar a mesma constante no pool do estagiário, em vez de fazer referência a várias instâncias diferentes do String que têm valores idênticos.

Esse método é pesquisado str no pool do estagiário. Se str já tiver sido InterNIC, uma referência a essa instância será retornada; caso contrário, null será retornado.

Compare esse método com o Intern método.

Esse método não retorna um valor booliano. Se você chamar o método porque deseja um valor booliano que indique se uma determinada cadeia de caracteres é interna, você pode usar um código como o seguinte.

C#
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.

Observação

Você pode substituir o uso do pool do estagiário ao usar Ngen.exe (gerador de imagem nativa) para instalar um assembly no cache de imagem nativa em um computador local. Para obter mais informações, consulte Considerações sobre desempenho na seção comentários da Intern propriedade.

Aplica-se a

Produto Versões
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8
.NET Standard 2.0, 2.1

Confira também