这两者之间有什么区别,我应该使用哪一个?
string s = "Hello world!";
String s = "Hello world!";
这两者之间有什么区别,我应该使用哪一个?
string s = "Hello world!";
String s = "Hello world!";
当前回答
最好的答案我曾经听说过关于使用提供的类型联盟在C#来自Jeffrey Richter在他的书CLR Via C#。
我已经看到一些开发人员混淆,不知道是否使用线条或线条在他们的代码. 因为在C#的线条(一个关键字)地图准确到System.String(一个FCL类型),没有区别,也可以使用。 在C#,长地图到System.Int64,但在不同的编程语言,很长时间可以地图到Int16或Int32. 事实上,C++/CLI实际上处理很长时间作为Int32. S
BinaryReader br = new BinaryReader(...);
float val = br.ReadSingle(); // OK, but feels unnatural
Single val = br.ReadSingle(); // OK and feels good
所以你有它,我认为这些都是很好的点,但是,我找不到自己在自己的代码中使用杰弗里的建议,也许我太困在我的C#世界里,但我最终试图让我的代码看起来像框架代码。
其他回答
实际上没有区别
关键字 C# 连接地图到.NET 类型的 System.String - 这是一个标签,保持到语言的名称公约。
上述的一切基本上是正确的,一个人可以检查它。
public static void Main()
{
var s = "a string";
}
编辑并打开.exe 与 ildasm 查看
.method private hidebysig static void Main(string[] args) cil managed
{
.entrypoint
// Code size 8 (0x8)
.maxstack 1
.locals init ([0] string s)
IL_0000: nop
IL_0001: ldstr "a string"
IL_0006: stloc.0
IL_0007: ret
} // end of method Program::Main
然后变成线条和线条,编译,打开与 ildasm 并看到 IL 不会改变. 它也显示语言的创作者在定义变量时更喜欢线条(spoiler:当呼叫会员时,他们更喜欢线条)。
坦率地说,在实践中通常没有System.String和 string之间的区别。
所有类型在 C# 是对象,所有衍生于 System.Object 类. 一个区别是,字符串是一个 C# 关键字,字符串可以用作变量名称. System.String 是这个类型的常规.NET 名称,字符串是方便的 C# 名称. 这里是一个简单的程序,显示 System.String 和字符串之间的区别。
string a = new string(new char[] { 'x', 'y', 'z' });
string b = new String(new char[] { 'x', 'y', 'z' });
String c = new string(new char[] { 'x', 'y', 'z' });
String d = new String(new char[] { 'x', 'y', 'z' });
MessageBox.Show((a.GetType() == typeof(String) && a.GetType() == typeof(string)).ToString()); // shows true
MessageBox.Show((b.GetType() == typeof(String) && b.GetType() == typeof(string)).ToString()); // shows true
MessageBox.Show((c.GetType() == typeof(String) && c.GetType() == typeof(string)).ToString()); // shows true
MessageBox.Show((d.GetType() == typeof(String) && d.GetType() == typeof(string)).ToString()); // shows true
@JonSkeet 在我的编辑器中
public enum Foo : UInt32 { }
我是Visual Studio 2015社区。
两者都是相同的,区别在于你如何使用它。
字符串为变量
String 是为了召唤其他 String 类方法
如:
string fName = "John";
string lName = "Smith";
string fullName = String.Concat(fName,lName);
if (String.IsNullOrEmpty(fName))
{
Console.WriteLine("Enter first name");
}
String 是 System.String 的意思,它是.NET Framework 类型. String 是 System.String 的 C# 语言中的一个字符串. 两者都编写到 System.String 在 IL (中间语言),所以没有区别. 选择你喜欢什么,并使用它. 如果你在 C# 中编码,我会更喜欢字符串,因为它是 C# 类型的字符串和由 C# 程序员熟悉。
我可以说同样的事情(int,System.Int32)等。