字符串和整数,隐式和显式 [英] Strings and ints, implicit and explicit

查看:128
本文介绍了字符串和整数,隐式和显式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果一位同事问我这个问题,并且在我脑子里迷茫的状态我没有答案:

Had a coworker ask me this, and in my brain befuddled state I didn't have an answer:

为什么你能这样做:

string ham = "ham " + 4;

但不是:

string ham = 4;

连接时,如果有字符串转换的隐式转换/操作,当分配为字符串时,为什么不一样? (当然没有做一些运算符重载)

If there's an implicit cast/operation for string conversion when you are concatenating, why not the same when assigning it as a string? (Without doing some operator overloading, of course)

推荐答案

当连接编译器时会转换语句ham + 4 调用 String.Concat ,这需要两个对象参数,所以将值 4 装箱,然后调用 ToString

When concatenating the compiler turns the statement "ham" + 4 into a call to String.Concat, which takes two object parameters, so the value 4 is boxed and then ToString is called on that.

对于赋值,没有从 int 隐式转换为 string ,因此您不能将 4 分配给字符串而不显式转换它。

For the assignment there is no implicit conversion from int to string, and thus you cannot assign 4 to a string without explicitly converting it.

换句话说,编译器对两个赋值的处理方式截然不同,尽管它们在C#中看起来非常相似。

In other words the two assignments are handled very differently by the compiler, despite the fact that they look very similar in C#.

这篇关于字符串和整数,隐式和显式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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