问题描述
在 C# 中,您可以隐式连接一个字符串,比如一个整数:
In C# you can implicitly concatenate a string and let's say, an integer:
string sth = "something" + 0;
我的问题是:
为什么,假设您可以隐式连接字符串和整数,C# 不允许像这样初始化字符串:
Why, by assuming the fact that you can implicitly concatenate a string and an int, C# disallows initializing strings like this:
string sth = 0; // Error: Cannot convert source type 'int' to target type 'string'
C# 如何将 0 转换为字符串.是 0.ToString()
还是 (string)0
还是别的什么?
How C# casts 0 as string. Is it 0.ToString()
or (string)0
or something else?
推荐答案
它编译为对 String.Concat(object, object)
,像这样:
It compiles to a call to String.Concat(object, object)
, like this:
string sth = String.Concat("something", 0);
(注意这一行实际上会被编译器优化掉)
(Note that this particular line will actually be optimized away by the compiler)
该方法定义如下:(摘自.Net参考源)
This method is defined as follows: (Taken from the .Net Reference Source)
public static String Concat(Object arg0, Object arg1) {
if (arg0==null) {
arg0 = String.Empty;
}
if (arg1==null) {
arg1 = String.Empty;
}
return Concat(arg0.ToString(), arg1.ToString());
}
(这调用了String.Concat(string, string)
)
要发现这一点,您可以使用 ildasm
或 Reflector(在 IL 或 C# 中,没有优化)来查看 +
行编译成什么.
To discover this, you can use ildasm
, or Reflector (in IL or in C# with no optimizations) to see what the +
line compiles to.
这篇关于string = string + int:幕后是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!