我正在阅读拳击和string.format().而且我了解到它会封装一个值类型,例如整数.
所以下面的代码会导致拳击
var number = 5;
var sampleString = string.Format("The number 5: {0}", number);
此代码将生成字符串
The number 5: 5
但是,如果我使用标准运算符连接,它仍会生成相同的字符串.
var sampleString = "The number 5: " + number;
这里发生了什么,这也是将整数转换为对象吗?
这也适用于日期对象,例如
var dateString = string.Format("The date: {0}", DateTime.Now);
var dateString = "The date: " + DateTime.Now;
我想第一行会打包,但第二行也不行?
解决方法:
对于:var dateString =“日期:”DateTime.Now;
将转换为String.Concat调用,并在您的代码中调用string.Concat(object,object)
重载.这将导致值类型DateTime.Now的装箱对象.
看看IL生成的.
.method private hidebysig static void Main(string[] args) cil managed
{
.entrypoint
// Code size 55 (0x37)
.maxstack 2
.locals init ([0] string dateString0,
[1] string dateString1)
IL_0000: ldstr "The date: {0}"
IL_0005: call valuetype [mscorlib]System.DateTime [mscorlib]System.DateTime::get_Now()
IL_000a: box [mscorlib]System.DateTime
IL_000f: call string [mscorlib]System.String::Format(string,
object)
IL_0014: stloc.0
IL_0015: ldstr "The date: "
IL_001a: call valuetype [mscorlib]System.DateTime [mscorlib]System.DateTime::get_Now()
IL_001f: box [mscorlib]System.DateTime
IL_0024: call string [mscorlib]System.String::Concat(object,
object)
IL_0029: stloc.1
IL_002a: ldloc.0
IL_002b: call void [mscorlib]System.Console::WriteLine(string)
IL_0030: ldloc.1
IL_0031: call void [mscorlib]System.Console::WriteLine(string)
IL_0036: ret
} // end of method Program::Main
正如您在IL中看到的,字符串连接转换为调用
IL_0024: call string [mscorlib]System.String::Concat(object,
object)
这是生成IL的代码
static void Main(string[] args)
{
var dateString0 = string.Format("The date: {0}", DateTime.Now);
var dateString1 = "The date: " + DateTime.Now;
Console.WriteLine(dateString0);
Console.WriteLine(dateString1);
}
如果是String.Format拳击也会发生.
标签:c,net,boxing 来源: https://codeday.me/bug/20190624/1276957.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。