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.

傳回

String

如果已經保留,則為系統的 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方法會使用實習集區來搜尋等於值的字串 strThe 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.

在下列範例中,字串 s1 (其值為 "MyTest")已經是暫留的,因為它是程式中的常值。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 1Intern 方法會還原為其在 .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 .NET Framework 1.0 and 1.1 with regard to interning the empty string. 在下列範例中,會將 str1 參考指派給變數 Empty ,並在將 str2 Empty Intern StringBuilder 值為字串的物件轉換後呼叫方法,以將參考指派給變數 EmptyIn 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. 然後,和中包含的參考 str1 str2 會進行比較是否相等。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 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1 和中 .NET Framework 3.0.NET Framework 3.0str1str2 不相等。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. 在所有其他版本中, str1str2 相等。In all other versions, str1 and str2 are 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. 首先,配置給暫存物件的記憶體,在 String common language runtime (CLR) 終止之前,不太可能釋出。First, the memory allocated for interned String objects is not likely to be released until the common language runtime (CLR) terminates. 原因是,在 String 您的應用程式(甚至是應用程式域)終止之後,CLR 對暫存物件的參考可能會保存下來。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.

CompilationRelaxations.NoStringInterning列舉成員將元件標記為不需要字串常值暫留。The CompilationRelaxations.NoStringInterning enumeration member marks an assembly as not requiring string-literal interning. 您可以 NoStringInterning 使用屬性套用至元件 CompilationRelaxationsAttributeYou can apply NoStringInterning to an assembly using the CompilationRelaxationsAttribute attribute. 此外,當您使用 Ngen.exe (原生映射 產生器) 在執行時間之前編譯元件時,不會在模組之間暫存字串。Also, when you use Ngen.exe (Native Image Generator) to compile an assembly in advance of run time, strings are not interned across modules.

適用於

另請參閱