本文介绍了难道"只读" (C#)减少内存使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中,并设置字段为只读减少内存使用?

In C#, does setting a field as readonly reduce memory usage?

DBRepository _db = new DBRepository();



VS

vs

readonly DBRepository _db = new DBRepository();



只是好奇。谢谢你。

Just curious. Thanks.

推荐答案

没有。

这意味着你不能分配给它除了在申报点或在构造函数中。您也可以不是或退出参数传递作为裁判的方法。

It means you can't assign to it except at the declaration point or in a constructor. You also can't pass it as a ref or out parameter to a method.

编辑:基于下面的评论。以下字段是只读,因为你希望来电者有的String.Empty 直接读取访问,但你不知道希望他们将其设置为别的东西。

based on the comment below. The following field is readonly because you want callers to have direct read access to string.Empty, but you don't want them to set it to something else.

public sealed class String
{
    public static readonly string Empty = "";
}



此外,有时当我有一个列表与LT;> ; 词典<> 在一个类中的字段,我将它声明只读,以表明我要与它的成员(甚至添加和删除项等)工作,但我从来没有想实际分配不同的列表或Dictionary对象吧。

Also, sometimes when I have a List<> or Dictionary<> as a field in a class, I'll declare it readonly to indicate that I want to work with its members (even Add and Remove items, etc.) but I never want to actually assign a different List or Dictionary object to it.

还有一个编辑:请确保您阅读有关过时的场(备注部分)来显示一个严重的问题,当你不明白,什么都有可能发生只读是与不是。

One more edit: Make sure you read about the deprecated Path.InvalidPathChars field (in the remarks section) to show a serious problem that can happen when you don't understand what readonly is and is not.

这篇关于难道&QUOT;只读&QUOT; (C#)减少内存使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 02:07