Resharper 总是建议我制作 const string 而不是 string
哪一个好:
string sQuery = "SELECT * FROM table";
或者
const string sQuery = "SELECT * FROM table";
为什么 resharper 总是建议我这样做?
which one is good:
string sQuery = "SELECT * FROM table";
or
const string sQuery = "SELECT * FROM table";
And why resharper always suggest me to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
后者更好 - 这意味着:
在从其他程序集访问和版本控制方面,“const”还有一些其他影响,但看起来这是一个私有字段,所以它不应该成为问题。 您可以大多数将其视为:
一般来说,我认为尽可能将字段设为静态是个好主意(如果它不随实例而变化,为什么它应该是实例变量?)并且尽可能只读(可变数据更难推理)。 如果您希望我详细介绍
static readonly
和const
之间的差异,请告诉我。The latter is better - it means that:
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:
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
andconst
.如果字符串永远不会改变并且永远不会在程序集之外使用,那么 const 是一个好主意。 如果它永远不会改变,但在程序集外部使用,静态只读可能是一个更好的主意 - 常量“烧入”在调用位置,而不是存储在一个位置,因此重新编译程序集包含 const 的代码不会更新依赖程序集——它们也必须重新编译。 另一方面,静态只读变量确实会在依赖程序集中更新。
If the string never changes and is never used outside your assembly, then const is a good idea. If it never changes but is used outside your assembly, static readonly might be a better idea -- consts are "burned in" at the site of the call, not stored in one location, so recompiling the assembly that contains the const does not update the dependent assemblies -- they have to be recompiled too. static readonly variables on the other hand do get updated in dependent assemblies.
仅当特定字符串引用从未更改时,ReSharper 才会建议这样做。 在这种情况下,您可以使用
const string
而不仅仅是string
来表达您的意图。ReSharper only suggests this if the particular string reference never changes. In that case you express your intend by using
const string
instead of juststring
.这样做是因为如果您不小心在代码中为 sQuery 分配了一个新值,如果它是一个 const,您将收到编译错误,因此它将在编译时捕获错误。 与将 ctor 中设置的成员变量设置为只读的建议相同
It does this because if you accidentally assign a new value to sQuery in your code, if it's a const you'll get a compile error, so it will catch a bug at compile time. Same with its suggestion to make member variables which are set in the ctor only to be readonly