System.String.IsInterned 方法

方法描述

检索对指定 String 的引用。

语法定义(C# System.String.IsInterned 方法 的用法)

public static string IsInterned(
	string str
)

参数/返回值

参数值/返回值 参数类型/返回类型 参数描述/返回描述
str System-String 要在暂存池中搜索的字符串。
返回值 System.String 如果 str 在公共语言运行时的暂存池中,则返回对它的引用;否则返回 null。

提示和注释

公共语言运行时会自动维护一个名为“暂存池”的表,它包含在程序中声明的每个唯一字符串常数的单个实例,以及以编程方式添加的 String 的任何唯一实例。

暂存池可以节约字符串存储区。 如果将字符串常数分配给几个变量,则每个变量设置为引用暂存池中的同一常数,而不是引用具有相同值的 String 的几个不同实例。

此方法在暂存池中查找 str。 如果已经将 str 放入暂存池中,则返回对此实例的引用;否则返回 null。

将此方法与 Intern 方法进行比较。

此方法不返回布尔值,但仍可以在需要布尔值的地方使用。

注意

从 .NET Framework 2.0 版开始,使用 Ngen.exe(本机映像生成器) 将某个程序集安装到本地计算机上的本机映像缓存时,可以重写暂存池的使用。 有关更多信息,请参见 Intern 属性“备注”部分中的“Performance Considerations”(性能注意事项)。

System.String.IsInterned 方法例子

下面的示例演示文本字符串自动由编译器留用的过程。

// Sample for String.IsInterned(String)
using System;
using System.Text;
using System.Runtime.CompilerServices;

// In the .NET Framework 2.0 the following attribute declaration allows you to 
// avoid the use of the interning when you use NGEN.exe to compile an assembly 
// to the native image cache.
[assembly: CompilationRelaxations(CompilationRelaxations.NoStringInterning)]
class Sample
{
    public static void Main()
    {
        // String str1 is known at compile time, and is automatically interned.
        String str1 = "abcd";

        // Constructed string, str2, is not explicitly or automatically interned.
        String str2 = new StringBuilder().Append("wx").Append("yz").ToString();
        Console.WriteLine();
        Test(1, str1);
        Test(2, str2);
    }

    public static void Test(int sequence, String str)
    {
        Console.Write("{0}) The string, '", sequence);
        String strInterned = String.IsInterned(str);
        if (strInterned == null)
            Console.WriteLine("{0}', is not interned.", str);
        else
            Console.WriteLine("{0}', is interned.", strInterned);
    }
}

//This example produces the following results:

//1) The string, 'abcd', is interned.
//2) The string, 'wxyz', is not interned.

//If you use NGEN.exe to compile the assembly to the native image cache, this
//example produces the following results:

//1) The string, 'abcd', is not interned.
//2) The string, 'wxyz', is not interned.

异常

异常 异常描述
ArgumentNullException str 为 null。

命名空间

namespace: System

程序集: mscorlib(在 mscorlib.dll 中)

版本信息

.NET Framework 受以下版本支持:4、3.5、3.0、2.0、1.1、1.0 .NET Framework Client Profile 受以下版本支持:4、3.5 SP1

适用平台

Windows 7, Windows Vista SP1 或更高版本, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008(不支持服务器核心), Windows Server 2008 R2(支持 SP1 或更高版本的服务器核心), Windows Server 2003 SP2 .NET Framework 并不是对每个平台的所有版本都提供支持。有关支持的版本的列表,请参见.NET Framework 系统要求。