相关疑难解决方法(0)

string = string + int:幕后是什么?

在C#中,你可以隐式地连接一个字符串,让我们说一个整数:

string sth = "something" + 0;
Run Code Online (Sandbox Code Playgroud)

我的问题是:

  1. 为什么,假设您可以隐式地连接字符串和int,C#不允许初始化字符串,如下所示:

    string sth = 0; // Error: Cannot convert source type 'int' to target type 'string'
    
    Run Code Online (Sandbox Code Playgroud)
  2. C#如何将0转换为字符串.它是0.ToString()或者(string)0还是其他什么东西?

  3. 如何找到上一个问题的答案?

c# string integer casting

51
推荐指数
2
解决办法
4万
查看次数

为什么在C#中使用String.Concat()?

我一直在想这个问题.为什么使用String.Concat()而不是使用plus运算符.我理解String.Format,因为它使用plus运算符空洞并使您的代码看起来更好.

比如说

string one = "bob";
string two = "jim";

string three = one + two;
string three = String.Concat(one, two);
Run Code Online (Sandbox Code Playgroud)

.net c# asp.net string

26
推荐指数
3
解决办法
2万
查看次数

自动.ToString()?

我有一个这样的方法:void m1(string str)并有一个这样的类:

public class MyClass
{
    public bool b1 { set; get; }

    //and other properties
}
Run Code Online (Sandbox Code Playgroud)

现在为什么下面的代码不会导致编译错误?

IClass2 _class2 = new Class2();
MyClass c1 = new MyClass();
_class2.m1("abcdef" + c1);
Run Code Online (Sandbox Code Playgroud)

当我调试它时,我意识到c1.ToString()已经传递给了m1.为什么会.ToString()发生这种自动?我唯一可以说的是m1已经在IClass2接口中定义并且已经实现了Class2.

.net c# interface tostring

3
推荐指数
2
解决办法
2754
查看次数

C#中的字符串连接与DateTime对象:为什么我的代码合法?

在我正在处理的一些C#代码中,一个DateTimeobject(dt)与两个字符串连接在一起:

string test = "This is a test " + dt + "...Why does this work?"
Run Code Online (Sandbox Code Playgroud)

这不会引发编译错误,并且工作正常.我的问题:为什么这是合法的?这是仅特定于DateTime对象,还是覆盖该ToString()方法的任何对象?

c# concatenation

2
推荐指数
1
解决办法
108
查看次数

标签 统计

c# ×4

.net ×2

string ×2

asp.net ×1

casting ×1

concatenation ×1

integer ×1

interface ×1

tostring ×1