String.Intern(String) 方法

定义

检索系统对指定 String 的引用。Retrieves the system's reference to the specified String.

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

参数

str
String

要在暂存池中搜索的字符串。A string to search for in the intern pool.

返回

如果暂存了 str,则返回系统对其的引用;否则返回对值为 str 的字符串的新引用。The system's reference to str, if it is interned; otherwise, a new reference to a string with the value of str.

异常

strnullstr is null.

示例

下面的示例使用三个相同值的字符串来确定新创建的字符串和暂存的字符串是否相等。The following example uses three strings that are equal in value to determine whether a newly created string and an interned string are equal.

// Sample for String::Intern(String)
using namespace System;
using namespace System::Text;
int main()
{
   String^ s1 = "MyTest";
   String^ s2 = (gcnew StringBuilder)->Append( "My" )->Append( "Test" )->ToString();
   String^ s3 = String::Intern( s2 );
   Console::WriteLine( "s1 == '{0}'", s1 );
   Console::WriteLine( "s2 == '{0}'", s2 );
   Console::WriteLine( "s3 == '{0}'", s3 );
   Console::WriteLine( "Is s2 the same reference as s1?: {0}", s2 == s1 );
   Console::WriteLine( "Is s3 the same reference as s1?: {0}", s3 == s1 );
}

/*
This example produces the following results:
s1 == 'MyTest'
s2 == 'MyTest'
s3 == 'MyTest'
Is s2 the same reference as s1?: False
Is s3 the same reference as s1?: True
*/
// Sample for String.Intern(String)
using System;
using System.Text;

class Sample
{
    public static void Main()
    {
        string s1 = "MyTest";
        string s2 = new StringBuilder().Append("My").Append("Test").ToString(); 
        string s3 = String.Intern(s2);
        Console.WriteLine($"s1 == {s1}");
        Console.WriteLine($"s2 == {s2}");
        Console.WriteLine($"s3 == {s3}");
        Console.WriteLine($"Is s2 the same reference as s1?: {(Object)s2 == (Object)s1}"); 
        Console.WriteLine($"Is s3 the same reference as s1?: {(Object)s3 == (Object)s1}");
    }
}
/*
This example produces the following results:
s1 == MyTest
s2 == MyTest
s3 == MyTest
Is s2 the same reference as s1?: False
Is s3 the same reference as s1?: True
*/
Imports System.Text

Class Sample

    Public Shared Sub Main()
        Dim s1 As String = "MyTest"
        Dim s2 As String = New StringBuilder().Append("My").Append("Test").ToString()
        Dim s3 As String = String.Intern(s2)
        Console.WriteLine($"s1 = {s1}")
        Console.WriteLine($"s2 = {s2}")
        Console.WriteLine($"s3 = {s3}")
        Console.WriteLine($"Is s2 the same reference as s1?: {s2 Is s1}")
        Console.WriteLine($"Is s3 the same reference as s1?: {s3 Is s1}")
    End Sub
End Class
'
's1 = MyTest
's2 = MyTest
's3 = MyTest
'Is s2 the same reference as s1?: False
'Is s3 the same reference as s1?: True
'

注解

公共语言运行时通过维护名为拘留池的表来节省字符串存储,该表包含对程序中以编程方式声明或创建的每个唯一文本字符串的单个引用。The common language runtime conserves string storage by maintaining a table, called the intern pool, that contains a single reference to each unique literal string declared or created programmatically in your program. 因此,系统中仅存在一个具有特定值的文本字符串的实例。Consequently, an instance of a literal string with a particular value only exists once in the system.

例如,如果将相同的文本字符串分配给几个变量,则运行时将从暂存池中检索到文本字符串的相同引用,并将其分配给每个变量。For example, if you assign the same literal string to several variables, the runtime retrieves the same reference to the literal string from the intern pool and assigns it to each variable.

Intern 方法使用拘留池搜索等于 str值的字符串。The Intern method uses the intern pool to search for a string equal to the value of str. 如果存在这样的字符串,则返回暂存池中的引用。If such a string exists, its reference in the intern pool is returned. 如果该字符串不存在,则会将对 str 的引用添加到拘留池中,然后返回该引用。If the string does not exist, a reference to str is added to the intern pool, then that reference is returned.

在下面的示例中,已暂存值为 "MyTest" 的字符串 s1,因为它是程序中的文本。In the following example, the string s1, which has a value of "MyTest", is already interned because it is a literal in the program. System.Text.StringBuilder 类将生成一个与 s1 具有相同值的新字符串对象。The System.Text.StringBuilder class generates a new string object that has the same value as s1. 对该字符串的引用将分配给 s2。A reference to that string is assigned to s2. Intern 方法搜索与 s2 具有相同值的字符串。The Intern method searches for a string that has the same value as s2. 由于存在这样的字符串,因此该方法将返回分配给 s1 的相同引用。Because such a string exists, the method returns the same reference that is assigned to s1. 然后,将该引用分配给 s3。That reference is then assigned to s3. 引用 s1 和 s2 比较不相等,因为它们引用不同的对象;引用 s1 和 s3 比较相等,因为它们引用相同的字符串。References s1 and s2 compare unequal because they refer to different objects; references s1 and s3 compare equal because they refer to the same string.

string s1 = "MyTest"; 
string s2 = new StringBuilder().Append("My").Append("Test").ToString(); 
string s3 = String.Intern(s2); 
Console.WriteLine((Object)s2==(Object)s1); // Different references.
Console.WriteLine((Object)s3==(Object)s1); // The same reference.
Dim s1 As String = "MyTest" 
Dim s2 As String = New StringBuilder().Append("My").Append("Test").ToString() 
Dim s3 As String = String.Intern(s2) 
Console.WriteLine(CObj(s2) Is CObj(s1))      ' Different references.
Console.WriteLine(CObj(s3) Is CObj(s1))      ' The same reference.

将此方法与 IsInterned 方法进行比较。Compare this method to the IsInterned method.

版本注意事项Version Considerations

.NET Framework 3.5 Service Pack 1.NET Framework 3.5 Service Pack 1中,Intern 方法会恢复到其在 .NET Framework 1.0 和1.1 中的行为,这与用于暂存空字符串有关。In the .NET Framework 3.5 Service Pack 1.NET Framework 3.5 Service Pack 1, the Intern method reverts to its behavior in the .NET Framework 1.0 and 1.1 with regard to interning the empty string. 在下面的示例中,为变量 str1 分配了对 Empty的引用,并为变量 str2 分配了对 Empty 的引用,该引用在转换其值 InternStringBuilder 对象之后调用 Empty一个字符串。In the following example, the variable str1 is assigned a reference to Empty, and the variable str2 is assigned the reference to Empty that is returned by calling the Intern method after converting a StringBuilder object whose value is Empty to a string. 然后,比较 str1str2 中包含的引用是否相等。Then the references contained in str1 and str2 are compared for equality.

string str1 = String.Empty;
string str2 = String.Empty;

StringBuilder sb = new StringBuilder().Append(String.Empty);
str2 = String.Intern(sb.ToString());	

if((object)str1==(object)str2)
    Console.WriteLine("The strings are equal.");
else
    Console.WriteLine("The strings are not equal.");
Dim str1 As String = String.Empty
Dim str2 As String = String.Empty

Dim sb As StringBuilder = New StringBuilder().Append(String.Empty)
str2 = String.Intern(sb.ToString())	

If CObj(str1) Is CObj(str2) Then
    Console.WriteLine("The strings are equal.")
Else
    Console.WriteLine("The strings are not equal.")
End If	

.NET Framework 1.0.NET Framework 1.0中,.NET Framework 1.1.NET Framework 1.1.NET Framework 3.5 SP1.NET Framework 3.5 SP1str1str2 相等。In the .NET Framework 1.0.NET Framework 1.0, .NET Framework 1.1.NET Framework 1.1, and .NET Framework 3.5 SP1.NET Framework 3.5 SP1, str1 and str2 are equal. .NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1.NET Framework 3.0.NET Framework 3.0中,str1str2 不相等。In the .NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1 and .NET Framework 3.0.NET Framework 3.0, str1 and str2 are not equal.

性能注意事项Performance Considerations

如果尝试减少应用程序分配的内存总量,请记住,暂存字符串具有两个不需要的副作用。If you are trying to reduce the total amount of memory your application allocates, keep in mind that interning a string has two unwanted side effects. 首先,在公共语言运行时(CLR)终止之前,为暂存 String 对象分配的内存不大可能被释放。First, the memory allocated for interned String objects is not likely to be released until the common language runtime (CLR) terminates. 原因在于,CLR 对暂存 String 对象的引用可在应用程序(甚至应用程序域)终止后保持。The reason is that the CLR's reference to the interned String object can persist after your application, or even your application domain, terminates. 其次,若要暂存字符串,必须先创建字符串。Second, to intern a string, you must first create the string. 即使将最终回收内存,也仍必须分配 String 对象使用的内存。The memory used by the String object must still be allocated, even though the memory will eventually be garbage collected.

.NET Framework 版本2.0 引入了 CompilationRelaxations.NoStringInterning 的枚举成员。The .NET Framework version 2.0 introduces the CompilationRelaxations.NoStringInterning enumeration member. NoStringInterning 成员将程序集标记为不需要字符串的暂留。The NoStringInterning member marks an assembly as not requiring string-literal interning. 您可以使用 CompilationRelaxationsAttribute 属性将 NoStringInterning 应用于程序集。You can apply NoStringInterning to an assembly using the CompilationRelaxationsAttribute attribute. 此外,当你使用ngen.exe (本机映像生成器)在运行时提前编译程序集时,不会在模块之间暂存字符串。Also, when you use the Ngen.exe (Native Image Generator) to compile an assembly in advance of run time, strings are not interned across modules.

适用于

另请参阅