Resharper总是建议我制作const字符串而不是string [英] Resharper always suggesting me to make const string instead of string

查看:89
本文介绍了Resharper总是建议我制作const字符串而不是string的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

哪个好:

string sQuery = "SELECT * FROM table";

const string sQuery = "SELECT * FROM table";

为什么为什么harshaper总是建议我这样做?

And why resharper always suggest me to do this?

推荐答案

后者更好-这意味着:


  • 这不是实例变量,因此在创建的每个实例中都不会得到多余的字符串引用

  • 您将无法更改变量(您可能不想这样做)

就从其他程序集和版本控制的访问而言, const还有其他影响,但看起来这是一个私人领域,所以这不应该成为问题。您可以主要认为它是:

There are some other effects of "const" in terms of access from other assemblies and versioning, but it looks like this is a private field so it shouldn't be an issue. You can mostly think of it as being:

static readonly string sQuery = ...;

总的来说,我相信将字段设置为静态是一个好主意(如果没有的话)因实例而异,为什么它应该是实例变量?)并且在可能的情况下为只读(可变数据更难推论)。让我知道是否要详细介绍静态只读 const 之间的区别。

In general I believe it's a good idea to make fields static when you can (if it doesn't vary by instance, why should it be an instance variable?) and read-only when you can (mutable data is harder to reason about). Let me know if you want me to go into the details of the differences between static readonly and const.

这篇关于Resharper总是建议我制作const字符串而不是string的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆