C# Intern() 方法用于检索对指定字符串的引用。它进入暂存池(内存区域)以搜索等于指定字符串的字符串。如果存在这样的字符串,则返回其在暂存池中的引用。如果字符串不存在,则将对指定 String 的引用添加到暂存池,然后返回该引用。
Intern()方法的签名如下:
public static string Intern(String str)
str:是字符串类型的参数。
using System;
public class StringExample
{
public static void Main(string[] args)
{
string s1 = "Hello C#";
string s2 = string.Intern(s1);
Console.WriteLine(s1);
Console.WriteLine(s2);
}
}
输出:
Hello C# Hello C#