简体   繁体   English

C# - 这个声明的字符串是否被视为const?

[英]C# - Is this declared string treated as a const?

Help me settle an argument here. 帮助我在这里解决争论。

Is this: 这是:

SqlCommand cmd = new SqlCommand( "sql cmd", conn);

treated exactly the same as this: 处理与此完全相同:

const string s = "sql cmd";
SqlCommand cmd = new SqlCommand( s, conn);

Ie. IE浏览器。 does it make a difference if I state specifically that the string s is a const. 如果我明确声明字符串s是const,它会有所作为。

And, if it is not treated in the same way, why not? 而且,如果没有以同样的方式对待,为什么不呢?

In the latter snippet, it's not that the string is const - it's that the variable is const. 在后面的代码片段中,并不是字符串是const - 而是变量是const。 This is not quite the same as const in C++. 这与C ++中的const不完全相同。 (Strings are always immutable in .NET.) (字符串在.NET中总是不可变的。)

And yes, the two snippets do the same thing. 是的,两个片段做同样的事情。 The only difference is that in the first form you'll have a metadata entry for s as well, and if the variable is declared at the type level (instead of being a local variable) then other methods could use it too. 唯一的区别是,在第一种形式中,你也将拥有s的元数据条目,如果变量是在类型级别声明的(而不是局部变量),那么其他方法也可以使用它。 Of course, due to string interning if you use "sql cmd" elsewhere you'll still only have a single string object in memory... but if you look at the type with reflection you'll find the const as a field in the metadata with the second snippet if it's declared as a constant field, and if it's just a local variable it'll be in the PDB file if you build one. 当然,由于字符串实习,如果你在其他地方使用“sql cmd”,你仍然只在内存中有一个字符串对象 ...但是如果你看一下带有反射的类型,你会发现const作为一个字段在第二个片段的元数据如果它被声明为常量字段,如果它只是一个局部变量,如果你构建一个,它将在PDB文件中。

The value of a const always gets burned directly into the caller, so yes they are identical. const的值总是直接烧到调用者,所以是的,它们是相同的。

Additionally, the compiler interns strings found in source code - a const is helpful if you are using the same string multiple times (purely from a maintenance angle - the result is the same either way). 另外,编译器实现了在源代码中找到的字符串 - 如果你多次使用相同的字符串,那么const很有用(纯粹来自维护角度 - 结果是相同的两种方式)。

SqlCommand的构造函数不会“看到”任何差异,因此将以相同的方式行事。

是的,那些完全一样。

Yes, feel free to use Reflector to look at the assembly, const strings will be replaced with literal strings on compilation. 是的,随意使用Reflector查看程序集,const字符串将在编译时替换为文字字符串。 I also have a blog post about this to safe you the work of using Reflector :) 我还有一篇关于此的博客文章 ,以保障您使用Reflector的工作:)

I'm not 100% sure about this, but I'd bet it is the same. 我不是100%肯定这一点,但我敢打赌它是一样的。

const will just make sure you don't reassing the variable, but it's something that can be done at compile time. const只会确保你没有重新定义变量,但它可以在编译时完成。

Morover, strings are inmutable, so I don't think it will make any difference declaring the variable or not. Morover,字符串是不可变的,所以我不认为声明变量会有什么不同。

However, the definite prove would be studing the IL code generated in both cases. 但是,明确的证据是研究在这两种情况下生成的IL代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM