다음을 통해 공유


String.Intern 메서드

지정된 String에 대한 시스템의 참조를 검색합니다.

네임스페이스: System
어셈블리: mscorlib(mscorlib.dll)

구문

‘선언
Public Shared Function Intern ( _
    str As String _
) As String
‘사용 방법
Dim str As String
Dim returnValue As String

returnValue = String.Intern(str)
public static string Intern (
    string str
)
public:
static String^ Intern (
    String^ str
)
public static String Intern (
    String str
)
public static function Intern (
    str : String
) : String

매개 변수

반환 값

str의 값이 이미 내부 풀에 추가되었으면 시스템 참조를 반환하고, 그렇지 않으면 str 값을 가진 문자열에 대한 새 참조를 반환합니다.

예외

예외 형식 조건

ArgumentNullException

str가 Null 참조(Visual Basic의 경우 Nothing)인 경우

설명

공용 언어 런타임은 내부 풀이라는 테이블을 유지함으로써 문자열을 저장합니다. 이 테이블에는 프로그램에서 프로그램 방식으로 만들어지거나 선언된 고유한 각 리터럴 문자열에 대한 단일 참조가 들어 있습니다. 따라서 특정한 값을 가진 리터럴 문자열의 인스턴스는 시스템에서 한 번만 존재합니다.

예를 들어 여러 변수에 같은 리터럴 문자열을 할당하는 경우 런타임은 내부 풀에서 리터럴 문자열에 대한 같은 참조를 검색해서 각 변수에 할당합니다.

Intern 메서드는 내부 풀을 사용하여 str의 값과 같은 문자열을 검색합니다. 문자열이 있으면 내부 풀의 참조가 반환됩니다. 문자열이 없으면 str에 대한 참조가 내부 풀에 추가되고 이 참조가 반환됩니다.

다음의 C# 예제에서 값이 "MyTest"인 문자열 s1은 프로그램의 리터럴이기 때문에 이미 내부 풀에 추가되어 있습니다.

System.Text.StringBuilder 클래스는 s1과 같은 값을 가진 새 문자열 개체를 생성합니다. 이 문자열에 대한 참조가 s2에 할당됩니다.

Intern 메서드는 s2와 같은 값을 가진 문자열을 검색합니다. 문자열이 있으므로 메서드는 s1에 할당된 것과 같은 참조를 반환하고 이 참조는 s3에 할당됩니다.

참조 s1과 s2는 다른 개체를 참조하기 때문에 같지 않은 것으로 간주되지만, 참조 s1과 s3는 같은 문자열을 참조하기 때문에 같은 것으로 간주됩니다.

 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.

이 메서드와 IsInterned 메서드를 비교해 보십시오.

버전 고려 사항

.NET Framework 버전 2.0부터는 Intern 메서드의 동작이 변경되었습니다. 다음 C# 코드 시퀀스에서는 Empty에 대한 참조를 str1 변수에 할당하고, Intern 메서드에서 반환하는 Empty에 대한 참조를 str2 변수에 할당하며, str1str2에 포함된 참조가 같은지 비교합니다.

string str1 = String.Empty;
string str2 = String.Intern(String.Empty);
if ((object) str1) == ((object) str2) …

.NET Framework 버전 1.1의 경우 str1str2가 같지 않지만 .NET Framework 버전 2.0부터는 str1str2가 같습니다.

성능 고려 사항

응용 프로그램에 의해 할당되는 총 메모리 양을 줄이려고 하는 경우 문자열을 내부 풀에 추가하면 다음과 같은 두 가지 원하지 않는 부작용이 발생할 수 있습니다. 첫째, 내부 풀에 추가된 String 개체에 할당된 메모리가 CLR(공용 언어 런타임)이 종료될 때까지 해제되지 않습니다. 이는 내부 풀에 추가된 String 개체에 대한 CLR의 참조가 응용 프로그램이나 심지어 응용 프로그램 도메인이 종료된 후에도 지속될 수 있기 때문입니다. 둘째, 문자열을 내부화하려면 먼저 문자열을 만들어야 합니다. 메모리가 가비지 수집되어도 String 개체에서 사용하는 메모리는 계속 할당된 채로 있어야 합니다.

예제

다음 코드 예제에서는 값이 같은 세 개의 문자열을 사용하여 새로 만든 문자열과 내부 풀에 추가된 문자열이 같은지 여부를 확인합니다.

' Sample for String.Intern(String)
Imports System
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 = '{0}'", s1)
      Console.WriteLine("s2 = '{0}'", s2)
      Console.WriteLine("s3 = '{0}'", s3)
      Console.WriteLine("Is s2 the same reference as s1?: {0}", s2 Is s1)
      Console.WriteLine("Is s3 the same reference as s1?: {0}", s3 Is s1)
   End Sub 'Main
End Class 'Sample
'
'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 == '{0}'", s1);
    Console.WriteLine("s2 == '{0}'", s2);
    Console.WriteLine("s3 == '{0}'", s3);
    Console.WriteLine("Is s2 the same reference as s1?: {0}", (Object)s2==(Object)s1); 
    Console.WriteLine("Is s3 the same reference as s1?: {0}", (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
*/
// 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)
import System.*;
import System.Text.*;

class Sample
{
    public static void main(String[] args)
    {
        String s1 = "MyTest";
        String s2 = (new 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}", 
            System.Convert.ToString((Object)s2 == (Object)s1));
        Console.WriteLine("Is s3 the same reference as s1?: {0}", 
            System.Convert.ToString((Object)s3 == (Object)s1));
    } //main
} //Sample
/*
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
*/

플랫폼

Windows 98, Windows 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

.NET Framework에서 모든 플래폼의 모든 버전을 지원하지는 않습니다. 지원되는 버전의 목록은 시스템 요구 사항을 참조하십시오.

버전 정보

.NET Framework

2.0, 1.1, 1.0에서 지원

.NET Compact Framework

2.0, 1.0에서 지원

참고 항목

참조

String 클래스
String 멤버
System 네임스페이스
IsInterned