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 SP1中,str1str2 相等。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. 首先,配置給留用 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. 原因是 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.

適用於

另請參閱