这两者之间有什么区别,我应该使用哪一个?
string s = "Hello world!";
String s = "Hello world!";
这两者之间有什么区别,我应该使用哪一个?
string s = "Hello world!";
String s = "Hello world!";
当前回答
如果有用的是真正看到没有线和System.String之间的区别:
var method1 = typeof(MyClass).GetMethod("TestString1").GetMethodBody().GetILAsByteArray();
var method2 = typeof(MyClass).GetMethod("TestString2").GetMethodBody().GetILAsByteArray();
//...
public string TestString1()
{
string str = "Hello World!";
return str;
}
public string TestString2()
{
String str = "Hello World!";
return str;
}
两者都产生相同的 IL 比特序列:
[ 0, 114, 107, 0, 0, 112, 10, 6, 11, 43, 0, 7, 42 ]
其他回答
最好的答案我曾经听说过关于使用提供的类型联盟在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#世界里,但我最终试图让我的代码看起来像框架代码。
有一个实用的区别在线和线之间。
nameof(String); // compiles
nameof(string); // doesn't compile
這是因為字符串是一個關鍵字(在這種情況下,一個名稱),而字符串是一個類型。
同样的情况也适用于其他联盟。
| Alias | Type |
|-----------|------------------|
| bool | System.Boolean |
| byte | System.Byte |
| sbyte | System.SByte |
| char | System.Char |
| decimal | System.Decimal |
| double | System.Double |
| float | System.Single |
| int | System.Int32 |
| uint | System.UInt32 |
| long | System.Int64 |
| ulong | System.UInt64 |
| object | System.Object |
| short | System.Int16 |
| ushort | System.UInt16 |
| string | System.String |
正如上面提到的那样,它们是相同的,而丝线只是对丝线的标志。
对于什么是值得的,我使用链来宣布类型 - 变量,属性,回报值和参数. 这与其他系统类型的使用一致 - int, bool, var 等(尽管 Int32 和 Boolean 也是正确的)。
我使用 String 在 String 类上使用静态方法,如 String.Split() 或 String.IsNullOrEmpty()。我觉得这更有意义,因为方法属于一个类,并且与我使用其他静态方法一致。
首先,两个字符串和字符串都不是相同的,有一个区别:字符串不是一个关键字,它可以用作识别器,而字符串是关键字,不能用作识别器。
我试图用不同的例子来解释: 首先,当我把字符串 s 放进 Visual Studio 并将它转移到我获得(没有颜色):
文档位于 https://msdn.microsoft.com/en-us/library/362314fe.aspx. 第二个句子说“string 是.NET 框架中的 String 的标志。
坦率地说,在实践中通常没有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社区。