这两者之间有什么区别,我应该使用哪一个?

string s = "Hello world!";
String s = "Hello world!";

当前回答

图像结果为 string vs String www.javatpoint.com 在 C# 中, string 是.NET 框架中的 string 类的 alias. 事实上,每个 C# 类型都有.NET 的同等值. 另一个小差异是,如果你使用 string 类,你需要进口系统名称空间,而你不需要在使用 string 关键词时进口名称空间。

其他回答

如果有用的是真正看到没有线和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 ]

string 是 System.String 的 C# 中的一个 alias. 所以技术上,没有区别. 它就像 int vs. System.Int32.

至于指导方针,一般建议在您提到对象时使用字符串。

吉。

string place = "world";

同样,我认为一般建议使用 String 如果你需要具体提到课堂。

吉。

string greet = String.Format("Hello {0}!", place);

这是微软在其例子中使用的风格。

似乎该领域的指导方针可能已经改变了,因为StyleCop现在强制使用C#特定的联盟。

字符串是关键词,你不能用字符串作为识别器。

条纹不是一个关键词,你可以用它作为一个标识:

例子

string String = "I am a string";

关键词行是 System.String 与关键词问题相同的标志,两者都是相同的。

 typeof(string) == typeof(String) == typeof(System.String)

System.String 是.NET 字符串类 - 在 C# 字符串中,它是 System.String 的标志 - 所以在使用中,它们是相同的。

至于指南,我不会过于沉默,只是使用你喜欢的东西 - 生活中有更多的重要事物,代码将是相同的,无论如何。

如果你找到自己的建造系统,需要指定你正在使用的整合器的尺寸,因此倾向于使用 Int16, Int32, UInt16, UInt32 等,那么它可能看起来更自然地使用 String - 并且在不同的.net 语言之间移动时,它可能会使事情更容易理解 - 否则我会使用 String 和 int。

下面的案例字符串是 System.String 的标志,它们在 C# 中是相同的。

有一个讨论是否应该使用系统类型(System.Int32,System.String等)类型或C#联盟(int, string等)。我个人认为你应该使用C#联盟,但这只是我的个人偏好。