加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 包装字符串的WeakReference导致奇怪的行为

发布时间:2020-12-15 23:45:59 所属栏目:百科 来源:网络整理
导读:我知道我应该将WeakReference仅用于大型对象,但我对以下场景感到好奇: object obj = 1; //Int32var wk = new WeakReference(obj);Console.WriteLine(wk.IsAlive); //Prints: Trueobj = null;GC.Collect(2,GCCollectionMode.Forced,true);Console.WriteLine(
我知道我应该将WeakReference仅用于大型对象,但我对以下场景感到好奇:

object obj = 1; //Int32

var wk = new WeakReference(obj);

Console.WriteLine(wk.IsAlive); //Prints: True

obj = null;

GC.Collect(2,GCCollectionMode.Forced,true);

Console.WriteLine(wk.IsAlive); //Prints: false,All Rigth!

到目前为止,没关系.

看看这个:

object obj = "test"; //String

var wk = new WeakReference(obj);

Console.WriteLine(wk.IsAlive); //Prints: True

obj = null;

GC.Collect(2,true);

Console.WriteLine(wk.IsAlive); //Prints: True,Why?

这是怎么回事?

解决方法

从String.Intern的评论:

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.

因此,您无法以编程方式发布另一个引用.稍微更改代码以在运行时生成实例会得到预期的结果:

object obj = new string(new char[] { 't','e','s','t' });
var wk = new WeakReference(obj);
Console.WriteLine(wk.IsAlive); //Prints: True
obj = null;
GC.Collect(2,true);
Console.WriteLine(wk.IsAlive); //Prints: False

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读