c#中字符串和字符串的区别是什么?

时间:2021-11-06 13:05:34

Example (note the case):

示例(注意的情况):

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

What are the guidelines for the use of each? And what are the differences?

使用它们的指导方针是什么?有什么区别呢?

56 个解决方案

#1


5016  

string is an alias in C# for System.String.
So technically, there is no difference. It's like int vs. System.Int32.

string是c#中System.String的别名。所以从技术上讲,没有区别。就像int和System.Int32。

As far as guidelines, it's generally recommended to use string any time you're referring to an object.

至于指导原则,通常建议在引用对象时使用string。

e.g.

如。

string place = "world";

Likewise, I think it's generally recommended to use String if you need to refer specifically to the class.

同样,我认为如果您需要特别引用类,一般建议使用String。

e.g.

如。

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

This is the style that Microsoft tends to use in their examples.

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


It appears that the guidance in this area may have changed, as StyleCop now enforces the use of the C# specific aliases.

这方面的指导似乎已经发生了变化,因为StyleCop现在强制使用c#特定的别名。

#2


2996  

Just for the sake of completeness, here's a brain dump of related information...

为了完整起见,这里有一个相关信息的大脑转储……

As others have noted, string is an alias for System.String. They compile to the same code, so at execution time there is no difference whatsoever. This is just one of the aliases in C#. The complete list is:

正如其他人所注意到的,string是System.String的别名。它们编译到相同的代码,因此在执行时没有任何区别。这只是c#中的别名之一。完整的列表:

object:  System.Object
string:  System.String
bool:    System.Boolean
byte:    System.Byte
sbyte:   System.SByte
short:   System.Int16
ushort:  System.UInt16
int:     System.Int32
uint:    System.UInt32
long:    System.Int64
ulong:   System.UInt64
float:   System.Single
double:  System.Double
decimal: System.Decimal
char:    System.Char

Apart from string and object, the aliases are all to value types. decimal is a value type, but not a primitive type in the CLR. The only primitive type which doesn't have an alias is System.IntPtr.

除了字符串和对象之外,别名都是值类型。decimal是值类型,而不是CLR中的基元类型。唯一没有别名的原始类型是System.IntPtr。

In the spec, the value type aliases are known as "simple types". Literals can be used for constant values of every simple type; no other value types have literal forms available. (Compare this with VB, which allows DateTime literals, and has an alias for it too.)

在规范中,值类型别名称为“简单类型”。文字可以用于每个简单类型的常量值;没有其他值类型有可用的文字形式。(与VB相比,VB允许使用DateTime常量,它也有一个别名)。

There is one circumstance in which you have to use the aliases: when explicitly specifying an enum's underlying type. For instance:

在一种情况下,您必须使用别名:显式指定枚举的底层类型时。例如:

public enum Foo : UInt32 {} // Invalid
public enum Bar : uint   {} // Valid

That's just a matter of the way the spec defines enum declarations - the part after the colon has to be the integral-type production, which is one token of sbyte, byte, short, ushort, int, uint, long, ulong, char... as opposed to a type production as used by variable declarations for example. It doesn't indicate any other difference.

这只是规范定义enum声明的方式——冒号后面的部分必须是集成类型的生产,它是sbyte, byte, short, ushort, int, long, ulong, char的一个标记。与变量声明使用的类型生成相反。它没有任何其他的区别。

Finally, when it comes to which to use: personally I use the aliases everywhere for the implementation, but the CLR type for any APIs. It really doesn't matter too much which you use in terms of implementation - consistency among your team is nice, but no-one else is going to care. On the other hand, it's genuinely important that if you refer to a type in an API, you do so in a language neutral way. A method called ReadInt32 is unambiguous, whereas a method called ReadInt requires interpretation. The caller could be using a language which defines an int alias for Int16, for example. The .NET framework designers have followed this pattern, good examples being in the BitConverter, BinaryReader and Convert classes.

最后,当涉及到哪一个使用时:我个人使用所有的别名来实现,但是任何api的CLR类型。在实现方面使用什么真的不重要——团队之间的一致性很好,但是没有人会在意。另一方面,非常重要的一点是,如果您引用API中的一个类型,那么您将以一种与语言无关的方式进行引用。一个叫做ReadInt32的方法是明确的,而一个叫做ReadInt的方法则需要解释。例如,调用者可以使用定义Int16的int别名的语言。. net框架设计者遵循了这种模式,在位转换器、BinaryReader和Convert类中都有很好的例子。

#3


595  

String stands for System.String and it is a .NET Framework type. string is an alias in the C# language for System.String. Both of them are compiled to System.String in IL (Intermediate Language), so there is no difference. Choose what you like and use that. If you code in C#, I'd prefer string as it's a C# type alias and well-known by C# programmers.

字符串代表系统。它是。net框架类型。string是c#语言中System.String的别名。它们都被编译成系统。在IL(中间语言)中的字符串,所以没有区别。选择你喜欢的并使用它。如果您用c#编写代码,我更喜欢string,因为它是c#类型的别名,c#程序员很熟悉它。

I can say the same about (int, System.Int32) etc..

我对(int, System.Int32)等也有同感。

#4


396  

The best answer I have ever heard about using the provided type aliases in C# comes from Jeffrey Richter in his book CLR Via C#. Here are his 3 reasons:

关于使用c#中提供的类型别名,我所听到的最好的答案来自Jeffrey Richter在他的书CLR中通过c#。以下是他的三个理由:

  • I've seen a number of developers confused, not knowing whether to use string or String in their code. Because in C# the string (a keyword) maps exactly to System.String (an FCL type), there is no difference and either can be used.
  • 我已经看到一些开发人员感到困惑,他们不知道在他们的代码中是否使用字符串或字符串。因为在c#中,字符串(关键字)完全映射到系统。字符串(FCL类型),没有区别,两者都可以使用。
  • In C#, long maps to System.Int64, but in a different programming language, long could map to an Int16 or Int32. In fact, C++/CLI does in fact treat long as an Int32. Someone reading source code in one language could easily misinterpret the code's intention if he or she were used to programming in a different programming language. In fact, most languages won't even treat long as a keyword and won't compile code that uses it.
  • 在c#中,长映射到系统。Int64,但是在另一种编程语言中,long可以映射到Int16或Int32。事实上,c++ /CLI实际上将long视为Int32。如果用一种语言阅读源代码的人习惯于使用另一种编程语言进行编程,那么他或她很容易误解代码的意图。事实上,大多数语言都不会将long作为关键字,也不会编译使用它的代码。
  • The FCL has many methods that have type names as part of their method names. For example, the BinaryReader type offers methods such as ReadBoolean, ReadInt32, ReadSingle, and so on, and the System.Convert type offers methods such as ToBoolean, ToInt32, ToSingle, and so on. Although it's legal to write the following code, the line with float feels very unnatural to me, and it's not obvious that the line is correct:
  • FCL有许多方法,这些方法的类型名称是它们方法名称的一部分。例如,BinaryReader类型提供了诸如ReadBoolean、ReadInt32、ReadSingle等方法,以及系统。Convert类型提供了ToBoolean、ToInt32、ToSingle等方法。虽然写下面的代码是合法的,但是浮点数的行对我来说是很不自然的,而且这行是否正确并不明显:
BinaryReader br = new BinaryReader(...);
float val  = br.ReadSingle(); // Ok, but feels unnatural
Single val = br.ReadSingle(); // OK and feels good

So there you have it. I think these are all really good points. I however, don't find myself using Jeffrey's advice in my own code. Maybe I am too stuck in my C# world but I end up trying to make my code look like the framework code.

这就是结果。我认为这些都是很好的观点。然而,我发现自己并没有在自己的代码中使用杰弗里的建议。也许我太困在c#世界里了,但是我最终尝试让我的代码看起来像框架代码。

#5


369  

string is a reserved word, but String is just a class name. This means that string cannot be used as a variable name by itself.

string是一个保留字,而string只是一个类名。这意味着字符串本身不能用作变量名。

If for some reason you wanted a variable called string, you'd see only the first of these compiles:

如果出于某种原因,您需要一个名为string的变量,那么您将只看到这些编译中的第一个:

StringBuilder String = new StringBuilder();  // compiles
StringBuilder string = new StringBuilder();  // doesn't compile 

If you really want a variable name called string you can use @ as a prefix:

如果你真的想要一个叫做字符串的变量名,你可以用@作为前缀:

StringBuilder @string = new StringBuilder();

Another critical difference: Stack Overflow highlights them differently.

另一个关键的区别是:堆栈溢出以不同的方式突出显示它们。

#6


320  

There is one difference - you can't use String without using System; beforehand.

有一个区别-你不能用不使用系统的字符串;事先。

#7


264  

It's been covered above; however, you can't use string in reflection; you must use String.

这是上面覆盖;但是,不能在反射中使用字符串;您必须使用字符串。

#8


197  

System.String is the .NET string class - in C# string is an alias for System.String - so in use they are the same.

系统。字符串是. net字符串类—在c#字符串中是系统的别名。字符串-所以在使用中它们是相同的。

As for guidelines I wouldn't get too bogged down and just use whichever you feel like - there are more important things in life and the code is going to be the same anyway.

至于指导方针,我不会太过纠结,随便用你喜欢的东西——生活中有更重要的东西,代码也会是一样的。

If you find yourselves building systems where it is necessary to specify the size of the integers you are using and so tend to use Int16, Int32, UInt16, UInt32 etc. then it might look more natural to use String - and when moving around between different .net languages it might make things more understandable - otherwise I would use string and int.

如果你发现自己构建系统,有必要指定要使用整数的大小,所以倾向于使用Int16,Int32,UInt16 UInt32等等,那么它可能看起来更自然使用字符串,当移动之间不同的。net语言可能会让事情更容易理解,否则我会使用字符串和整数。

#9


163  

I prefer the capitalized .NET types (rather than the aliases) for formatting reasons. The .NET types are colored the same as other object types (the value types are proper objects, after all).

出于格式化的原因,我更喜欢大写的。net类型(而不是别名)。. net类型的颜色与其他对象类型相同(值类型毕竟是适当的对象)。

Conditional and control keywords (like if, switch, and return) are lowercase and colored dark blue (by default). And I would rather not have the disagreement in use and format.

条件和控制关键字(如if、switch和return)是小写的,颜色为深蓝色(默认情况下)。我不希望在使用和格式上有分歧。

Consider:

考虑:

String someString; 
string anotherString; 

#10


162  

string and String are identical in all ways (except the uppercase "S"). There are no performance implications either way.

字符串和字符串在所有方面都是相同的(除了大写的“S”)。这两种方式都不影响性能。

Lowercase string is preferred in most projects due to the syntax highlighting

由于语法突出显示,在大多数项目中,小写字符串是首选

#11


150  

C# is a language which is used together with the CLR.

c#是一种与CLR一起使用的语言。

string is a type in C#.

字符串是c#中的一种类型。

System.String is a type in the CLR.

系统。字符串是CLR中的一种类型。

When you use C# together with the CLR string will be mapped to System.String.

当您使用c#和CLR字符串一起使用时,将映射到System.String。

Theoretically, you could implement a C#-compiler that generated Java bytecode. A sensible implementation of this compiler would probably map string to java.lang.String in order to interoperate with the Java runtime library.

理论上,您可以实现生成Java字节码的c#编译器。这个编译器的合理实现可能会将字符串映射到java.lang。字符串,以便与Java运行时库进行互操作。

#12


136  

This YouTube video demonstrates practically how they differ.

这个YouTube视频展示了他们的不同之处。

But now for a long textual answer.

但现在我们来看一个长篇大论的答案。

When we talk about .NET there are two different things one there is .NET framework and the other there are languages ( C# , VB.NET etc) which use that framework.

当我们讨论。net时,有两种不同的东西,一种是。net框架,另一种是语言(c#, VB)使用那个框架的。

c#中字符串和字符串的区别是什么?

"System.String" a.k.a "String" ( capital "S") is a .NET framework data type while "string" is a C# data type.

”系统。“a.k.字符串。“String”(大写“S”)是。net框架数据类型,而“String”是c#数据类型。

c#中字符串和字符串的区别是什么?

In short "String" is an alias ( the same thing called with different names) of "string". So technically both the below code statements will give the same output.

简而言之,“String”是“String”的别名(用不同名称调用的同一事物)。因此,技术上来说,下面的代码语句将给出相同的输出。

String s = "I am String";

or

string s = "I am String";

In the same way there are aliases for other c# data type as shown below:-

同样的,还有其他c#数据类型的别名,如下所示:-

object: System.Object, string: System.String, bool: System.Boolean, byte: System.Byte, sbyte: System.SByte, short: System.Int16 and so on

对象:系统。字符串对象:系统。字符串,bool:系统。布尔,字节:系统。字节,sbyte:系统。SByte短:系统。Int16等等

Now the million dollar question from programmer's point of view So when to use "String" and "string"?

现在从程序员的角度来看这个百万美元的问题那么什么时候使用"String"和"String"呢?

First thing to avoid confusion use one of them consistently. But from best practices perspective when you do variable declaration it's good to use "string" ( small "s") and when you are using it as a class name then "String" ( capital "S") is preferred.

避免混淆的第一件事就是始终使用其中之一。但是,从最佳实践的角度来看,当您进行变量声明时,最好使用“string”(小写的“s”),当您将它用作类名时,最好使用“string”(大写的“s”)。

In the below code the left hand side is a variable declaration and it declared using "string". At the right hand side we are calling a method so "String" is more sensible.

在下面的代码中,左边是一个变量声明,它使用“string”声明。在右边,我们调用一个方法,因此“String”更合理。

string s = String.ToUpper() ;

#13


127  

string is just an alias for System.String. The compiler will treat them identically.

string只是System.String的别名。编译器会对它们一视同仁。

The only practical difference is the syntax highlighting as you mention, and that you have to write using System if you use String.

惟一的实际区别是语法突出显示,正如您所提到的,如果使用字符串,则必须使用System编写。

#14


120  

Lower case string is an alias for System.String. They are the same in C#.

小写字符串是System.String的别名。它们在c#中是一样的。

There's a debate over whether you should use the System types (System.Int32, System.String, etc.) types or the C# aliases (int, string, etc). I personally believe you should use the C# aliases, but that's just my personal preference.

关于是否应该使用系统类型(System)存在争论。Int32,系统。类型或c#别名(int, String,等等)。我个人认为你应该使用c#别名,但这只是我个人的偏好。

#15


113  

Both are same. But from coding guidelines perspective it's better to use string instead of String. This is what generally developers use. e.g. instead of using Int32 we use int as int is alias to Int32

两者都是相同的。但是从编码指南的角度来看,最好使用字符串而不是字符串。这是开发人员通常使用的。我们用int代替Int32,因为int是Int32的别名

FYI “The keyword string is simply an alias for the predefined class System.String.” - C# Language Specification 4.2.3 http://msdn2.microsoft.com/En-US/library/aa691153.aspx

关键字字符串只是预定义类System.String的别名。- c#语言规范4.2.3 http://msdn2.microsoft.com/En-US/library/aa691153.aspx

#16


96  

As the others are saying, they're the same. StyleCop rules, by default, will enforce you to use string as a C# code style best practice, except when referencing System.String static functions, such as String.Format, String.Join, String.Concat, etc...

正如其他人所说,他们是一样的。默认情况下,StyleCop规则将强制您使用string作为c#代码样式的最佳实践,除非引用系统。字符串静态函数,如字符串。格式字符串。加入,字符串。Concat等等……

#17


78  

Using System types makes it easier to port between C# and VB.Net, if you are into that sort of thing.

使用系统类型可以更容易地在c#和VB之间移植。Net,如果你喜欢这种东西。

#18


73  

Against what seems to be common practice among other programmers, I prefer String over string, just to highlight the fact that String is a reference type, as Jon Skeet mentioned.

与其他程序员常见的做法相反,我更喜欢字符串而不是字符串,只是强调一下,正如Jon Skeet所提到的,字符串是一种引用类型。

#19


68  

string is an alias (or shorthand) of System.String. That means, by typing string we meant System.String. You can read more in think link: 'string' is an alias/shorthand of System.String.

string是System.String的别名(或简写)。这意味着,通过输入string我们意味着System.String。您可以在think link中阅读更多内容:“string”是System.String的别名/简写。

#20


61  

String (System.String) is a class in the base class library. string (lower case) is a reserved work in C# that is an alias for System.String. Int32 vs int is a similar situation as is Boolean vs. bool. These C# language specific keywords enable you to declare primitives in a style similar to C.

String (System.String)是基类库中的一个类。string(小写)是c#中的保留工作,是System.String的别名。Int32 vs int与Boolean与bool的情况类似。这些c#语言特定的关键字使您能够以类似于C的样式声明原语。

#21


54  

String is not a keyword and it can be used as Identifier whereas string is a keyword and cannot be used as Identifier. And in function point of view both are same.

String不是关键字,它可以用作标识符,而String是关键字,不能用作标识符。从功能的角度来看,两者都是一样的。

#22


54  

Coming late to the party: I use the CLR types 100% of the time (well, except if forced to use the C# type, but I don't remember when the last time that was).

聚会迟到:我100%使用CLR类型(除了*使用c#类型,但我不记得上次是什么时候)。

I originally started doing this years ago, as per the CLR books by Ritchie. It made sense to me that all CLR languages ultimately have to be able to support the set of CLR types, so using the CLR types yourself provided clearer, and possibly more "reusable" code.

我最初是在几年前开始做这件事的,根据里奇的CLR书籍。对我来说,所有CLR语言最终都必须能够支持CLR类型的集合是有意义的,因此使用CLR类型本身可以提供更清晰、可能更“可重用”的代码。

Now that I've been doing it for years, it's a habit and I like the coloration that VS shows for the CLR types.

现在我已经做了好几年了,这是一种习惯,我喜欢VS为CLR类型显示的颜色。

The only real downer is that auto-complete uses the C# type, so I end up re-typing automatically generated types to specify the CLR type instead.

唯一令人沮丧的是,自动补全使用c#类型,因此我最终重新输入自动生成的类型来指定CLR类型。

Also, now, when I see "int" or "string", it just looks really wrong to me, like I'm looking at 1970's C code.

而且,现在,当我看到int或者string时,我觉得它看起来很不对,就像我在看1970年的C代码。

#23


47  

I'd just like to add this to lfousts answer, from Ritchers book:

我想补充一下lfousts的回答,来自Ritchers的书:

The C# language specification states, “As a matter of style, use of the keyword is favored over use of the complete system type name.” I disagree with the language specification; I prefer to use the FCL type names and completely avoid the primitive type names. In fact, I wish that compilers didn’t even offer the primitive type names and forced developers to use the FCL type names instead. Here are my reasons:

c#语言规范说,“就风格而言,使用关键字比使用完整的系统类型名更受欢迎。”“我不同意语言规范;我更喜欢使用FCL类型名,并完全避免使用原始类型名。事实上,我希望编译器甚至不提供原始类型名称,并强迫开发人员使用FCL类型名称。下面是我的理由:

I didn't get his opinion before I read the complete paragraph.

在我读完整段之前,我没有得到他的意见。

#24


41  

It's a matter of convention, really. "string" just looks more like C/C++ style. The general convention is to use whatever shortcuts your chosen language has provided (int/Int for Int32). This goes for "object" and "decimal" as well.

这是一个惯例,真的。“string”看起来更像C/ c++风格。一般约定是使用您所选择的语言提供的任何快捷方式(int/ int为Int32)。这也适用于“对象”和“十进制”。

Theoretically this could help to port code into some future 64-bit standard in which "int" might mean Int64, but that's not the point, and I would expect any upgrade wizard to change any "int" references to "Int32" anyway just to be safe.

理论上,这有助于将代码移植到未来的64位标准中,其中“int”可能表示Int64,但这不是重点,我希望任何升级向导都能将任何“int”引用修改为“Int32”,以确保安全。

#25


40  

There is no difference.

没有区别。

The C# keyword string maps to the .NET type System.String - it is an alias that keeps to the naming conventions of the language.

c#关键字字符串映射到。net类型系统。字符串——它是一个别名,保留了语言的命名约定。

Similarly, int maps to System.Int32.

同样,int映射到System.Int32。

#26


39  

New answer after 6 years and 5 months (procrastination).

6年5个月后的新答案(拖延症)。

While string is a reserved C# keyword that always has a fixed meaning, String is just an ordinary identifier which could refer to anything. Depending on members of the current type, the current namespace and the applied using directives and their placement, String could be a value or a type distinct from global::System.String.

string是一个保留的c#关键字,总是有固定的含义,string只是一个普通的标识符,可以指向任何东西。根据当前类型的成员、当前名称空间和应用的使用指令及其位置,字符串可以是值或类型,与global: System.String不同。

I shall provide two examples where using directives will not help.

我将提供两个使用指示不会有帮助的示例。


First, when String is a value of the current type (or a local variable):

首先,当字符串是当前类型(或局部变量)的值时:

class MySequence<TElement>
{
  public IEnumerable<TElement> String { get; set; }

  void Example()
  {
    var test = String.Format("Hello {0}.", DateTime.Today.DayOfWeek);
  }
}

The above will not compile because IEnumerable<> does not have a non-static member called Format, and no extension methods apply. In the above case, it may still be possible to use String in other contexts where a type is the only possibility syntactically. For example String local = "Hi mum!"; could be OK (depending on namespace and using directives).

上面的内容不会编译,因为IEnumerable<>没有一个非静态成员称为格式,也不应用扩展方法。在上述情况下,可能仍然可以在其他情况下使用字符串,其中类型是惟一可能的语法。例如字符串local =“Hi mum!”;可能没问题(取决于命名空间和使用指令)。

Worse: Saying String.Concat(someSequence) will likely (depending on usings) go to the Linq extension method Enumerable.Concat. It will not go to the static method string.Concat.

更糟的是:说String.Concat(someSequence)可能(取决于使用情况)转到Linq扩展方法Enumerable.Concat。它不会进入静态方法。


Secondly, when String is another type, nested inside the current type:

其次,当字符串是另一种类型时,嵌套在当前类型中:

class MyPiano
{
  protected class String
  {
  }

  void Example()
  {
    var test1 = String.Format("Hello {0}.", DateTime.Today.DayOfWeek);
    String test2 = "Goodbye";
  }
}

Neither statement in the Example method compiles. Here String is always a piano string, MyPiano.String. No member (static or not) Format exists on it (or is inherited from its base class). And the value "Goodbye" cannot be converted into it.

示例方法中的任何语句都不会编译。这里的弦总是钢琴弦,我的钢琴弦。它上不存在任何成员(静态或非静态)格式(或从基类继承)。“再见”的值不能转换成它。

#27


34  

string is a keyword, and you can't use string as an identifier.

字符串是关键字,不能使用字符串作为标识符。

String is not a keyword, and you can use it as an identifier:

String不是关键字,您可以将它用作标识符:

Example

例子

string String = "I am a string";

The keyword string is an alias for System.String aside from the keyword issue, the two are exactly equivalent.

关键字字符串是系统的别名。除了关键字问题之外,这两者是完全等价的。

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

#28


34  

There's a quote on this issue from Daniel Solis' book.

在丹尼尔·索利斯的书中有这样一段话。

All the predefined types are mapped directly to underlying .NET types. The C# type names (string) are simply aliases for the .NET types (String or System.String), so using the .NET names works fine syntactically, although this is discouraged. Within a C# program, you should use the C# names rather than the .NET names.

所有预定义类型都直接映射到底层的。net类型。c#类型名称(string)只是. net类型(string或System.String)的别名,因此使用. net名称在语法上很有用,尽管不建议这样做。在c#程序中,您应该使用c#名称而不是。net名称。

#29


33  

Yes, that's no difference between them, just like the bool and Boolean.

是的,它们之间没有区别,就像布尔和布尔一样。

#30


30  

There is no difference between the two - string, however, appears to be the preferred option when considering other developers' source code.

然而,在考虑其他开发人员的源代码时,这两个字符串似乎是首选的选项。

#1


5016  

string is an alias in C# for System.String.
So technically, there is no difference. It's like int vs. System.Int32.

string是c#中System.String的别名。所以从技术上讲,没有区别。就像int和System.Int32。

As far as guidelines, it's generally recommended to use string any time you're referring to an object.

至于指导原则,通常建议在引用对象时使用string。

e.g.

如。

string place = "world";

Likewise, I think it's generally recommended to use String if you need to refer specifically to the class.

同样,我认为如果您需要特别引用类,一般建议使用String。

e.g.

如。

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

This is the style that Microsoft tends to use in their examples.

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


It appears that the guidance in this area may have changed, as StyleCop now enforces the use of the C# specific aliases.

这方面的指导似乎已经发生了变化,因为StyleCop现在强制使用c#特定的别名。

#2


2996  

Just for the sake of completeness, here's a brain dump of related information...

为了完整起见,这里有一个相关信息的大脑转储……

As others have noted, string is an alias for System.String. They compile to the same code, so at execution time there is no difference whatsoever. This is just one of the aliases in C#. The complete list is:

正如其他人所注意到的,string是System.String的别名。它们编译到相同的代码,因此在执行时没有任何区别。这只是c#中的别名之一。完整的列表:

object:  System.Object
string:  System.String
bool:    System.Boolean
byte:    System.Byte
sbyte:   System.SByte
short:   System.Int16
ushort:  System.UInt16
int:     System.Int32
uint:    System.UInt32
long:    System.Int64
ulong:   System.UInt64
float:   System.Single
double:  System.Double
decimal: System.Decimal
char:    System.Char

Apart from string and object, the aliases are all to value types. decimal is a value type, but not a primitive type in the CLR. The only primitive type which doesn't have an alias is System.IntPtr.

除了字符串和对象之外,别名都是值类型。decimal是值类型,而不是CLR中的基元类型。唯一没有别名的原始类型是System.IntPtr。

In the spec, the value type aliases are known as "simple types". Literals can be used for constant values of every simple type; no other value types have literal forms available. (Compare this with VB, which allows DateTime literals, and has an alias for it too.)

在规范中,值类型别名称为“简单类型”。文字可以用于每个简单类型的常量值;没有其他值类型有可用的文字形式。(与VB相比,VB允许使用DateTime常量,它也有一个别名)。

There is one circumstance in which you have to use the aliases: when explicitly specifying an enum's underlying type. For instance:

在一种情况下,您必须使用别名:显式指定枚举的底层类型时。例如:

public enum Foo : UInt32 {} // Invalid
public enum Bar : uint   {} // Valid

That's just a matter of the way the spec defines enum declarations - the part after the colon has to be the integral-type production, which is one token of sbyte, byte, short, ushort, int, uint, long, ulong, char... as opposed to a type production as used by variable declarations for example. It doesn't indicate any other difference.

这只是规范定义enum声明的方式——冒号后面的部分必须是集成类型的生产,它是sbyte, byte, short, ushort, int, long, ulong, char的一个标记。与变量声明使用的类型生成相反。它没有任何其他的区别。

Finally, when it comes to which to use: personally I use the aliases everywhere for the implementation, but the CLR type for any APIs. It really doesn't matter too much which you use in terms of implementation - consistency among your team is nice, but no-one else is going to care. On the other hand, it's genuinely important that if you refer to a type in an API, you do so in a language neutral way. A method called ReadInt32 is unambiguous, whereas a method called ReadInt requires interpretation. The caller could be using a language which defines an int alias for Int16, for example. The .NET framework designers have followed this pattern, good examples being in the BitConverter, BinaryReader and Convert classes.

最后,当涉及到哪一个使用时:我个人使用所有的别名来实现,但是任何api的CLR类型。在实现方面使用什么真的不重要——团队之间的一致性很好,但是没有人会在意。另一方面,非常重要的一点是,如果您引用API中的一个类型,那么您将以一种与语言无关的方式进行引用。一个叫做ReadInt32的方法是明确的,而一个叫做ReadInt的方法则需要解释。例如,调用者可以使用定义Int16的int别名的语言。. net框架设计者遵循了这种模式,在位转换器、BinaryReader和Convert类中都有很好的例子。

#3


595  

String stands for System.String and it is a .NET Framework type. string is an alias in the C# language for System.String. Both of them are compiled to System.String in IL (Intermediate Language), so there is no difference. Choose what you like and use that. If you code in C#, I'd prefer string as it's a C# type alias and well-known by C# programmers.

字符串代表系统。它是。net框架类型。string是c#语言中System.String的别名。它们都被编译成系统。在IL(中间语言)中的字符串,所以没有区别。选择你喜欢的并使用它。如果您用c#编写代码,我更喜欢string,因为它是c#类型的别名,c#程序员很熟悉它。

I can say the same about (int, System.Int32) etc..

我对(int, System.Int32)等也有同感。

#4


396  

The best answer I have ever heard about using the provided type aliases in C# comes from Jeffrey Richter in his book CLR Via C#. Here are his 3 reasons:

关于使用c#中提供的类型别名,我所听到的最好的答案来自Jeffrey Richter在他的书CLR中通过c#。以下是他的三个理由:

  • I've seen a number of developers confused, not knowing whether to use string or String in their code. Because in C# the string (a keyword) maps exactly to System.String (an FCL type), there is no difference and either can be used.
  • 我已经看到一些开发人员感到困惑,他们不知道在他们的代码中是否使用字符串或字符串。因为在c#中,字符串(关键字)完全映射到系统。字符串(FCL类型),没有区别,两者都可以使用。
  • In C#, long maps to System.Int64, but in a different programming language, long could map to an Int16 or Int32. In fact, C++/CLI does in fact treat long as an Int32. Someone reading source code in one language could easily misinterpret the code's intention if he or she were used to programming in a different programming language. In fact, most languages won't even treat long as a keyword and won't compile code that uses it.
  • 在c#中,长映射到系统。Int64,但是在另一种编程语言中,long可以映射到Int16或Int32。事实上,c++ /CLI实际上将long视为Int32。如果用一种语言阅读源代码的人习惯于使用另一种编程语言进行编程,那么他或她很容易误解代码的意图。事实上,大多数语言都不会将long作为关键字,也不会编译使用它的代码。
  • The FCL has many methods that have type names as part of their method names. For example, the BinaryReader type offers methods such as ReadBoolean, ReadInt32, ReadSingle, and so on, and the System.Convert type offers methods such as ToBoolean, ToInt32, ToSingle, and so on. Although it's legal to write the following code, the line with float feels very unnatural to me, and it's not obvious that the line is correct:
  • FCL有许多方法,这些方法的类型名称是它们方法名称的一部分。例如,BinaryReader类型提供了诸如ReadBoolean、ReadInt32、ReadSingle等方法,以及系统。Convert类型提供了ToBoolean、ToInt32、ToSingle等方法。虽然写下面的代码是合法的,但是浮点数的行对我来说是很不自然的,而且这行是否正确并不明显:
BinaryReader br = new BinaryReader(...);
float val  = br.ReadSingle(); // Ok, but feels unnatural
Single val = br.ReadSingle(); // OK and feels good

So there you have it. I think these are all really good points. I however, don't find myself using Jeffrey's advice in my own code. Maybe I am too stuck in my C# world but I end up trying to make my code look like the framework code.

这就是结果。我认为这些都是很好的观点。然而,我发现自己并没有在自己的代码中使用杰弗里的建议。也许我太困在c#世界里了,但是我最终尝试让我的代码看起来像框架代码。

#5


369  

string is a reserved word, but String is just a class name. This means that string cannot be used as a variable name by itself.

string是一个保留字,而string只是一个类名。这意味着字符串本身不能用作变量名。

If for some reason you wanted a variable called string, you'd see only the first of these compiles:

如果出于某种原因,您需要一个名为string的变量,那么您将只看到这些编译中的第一个:

StringBuilder String = new StringBuilder();  // compiles
StringBuilder string = new StringBuilder();  // doesn't compile 

If you really want a variable name called string you can use @ as a prefix:

如果你真的想要一个叫做字符串的变量名,你可以用@作为前缀:

StringBuilder @string = new StringBuilder();

Another critical difference: Stack Overflow highlights them differently.

另一个关键的区别是:堆栈溢出以不同的方式突出显示它们。

#6


320  

There is one difference - you can't use String without using System; beforehand.

有一个区别-你不能用不使用系统的字符串;事先。

#7


264  

It's been covered above; however, you can't use string in reflection; you must use String.

这是上面覆盖;但是,不能在反射中使用字符串;您必须使用字符串。

#8


197  

System.String is the .NET string class - in C# string is an alias for System.String - so in use they are the same.

系统。字符串是. net字符串类—在c#字符串中是系统的别名。字符串-所以在使用中它们是相同的。

As for guidelines I wouldn't get too bogged down and just use whichever you feel like - there are more important things in life and the code is going to be the same anyway.

至于指导方针,我不会太过纠结,随便用你喜欢的东西——生活中有更重要的东西,代码也会是一样的。

If you find yourselves building systems where it is necessary to specify the size of the integers you are using and so tend to use Int16, Int32, UInt16, UInt32 etc. then it might look more natural to use String - and when moving around between different .net languages it might make things more understandable - otherwise I would use string and int.

如果你发现自己构建系统,有必要指定要使用整数的大小,所以倾向于使用Int16,Int32,UInt16 UInt32等等,那么它可能看起来更自然使用字符串,当移动之间不同的。net语言可能会让事情更容易理解,否则我会使用字符串和整数。

#9


163  

I prefer the capitalized .NET types (rather than the aliases) for formatting reasons. The .NET types are colored the same as other object types (the value types are proper objects, after all).

出于格式化的原因,我更喜欢大写的。net类型(而不是别名)。. net类型的颜色与其他对象类型相同(值类型毕竟是适当的对象)。

Conditional and control keywords (like if, switch, and return) are lowercase and colored dark blue (by default). And I would rather not have the disagreement in use and format.

条件和控制关键字(如if、switch和return)是小写的,颜色为深蓝色(默认情况下)。我不希望在使用和格式上有分歧。

Consider:

考虑:

String someString; 
string anotherString; 

#10


162  

string and String are identical in all ways (except the uppercase "S"). There are no performance implications either way.

字符串和字符串在所有方面都是相同的(除了大写的“S”)。这两种方式都不影响性能。

Lowercase string is preferred in most projects due to the syntax highlighting

由于语法突出显示,在大多数项目中,小写字符串是首选

#11


150  

C# is a language which is used together with the CLR.

c#是一种与CLR一起使用的语言。

string is a type in C#.

字符串是c#中的一种类型。

System.String is a type in the CLR.

系统。字符串是CLR中的一种类型。

When you use C# together with the CLR string will be mapped to System.String.

当您使用c#和CLR字符串一起使用时,将映射到System.String。

Theoretically, you could implement a C#-compiler that generated Java bytecode. A sensible implementation of this compiler would probably map string to java.lang.String in order to interoperate with the Java runtime library.

理论上,您可以实现生成Java字节码的c#编译器。这个编译器的合理实现可能会将字符串映射到java.lang。字符串,以便与Java运行时库进行互操作。

#12


136  

This YouTube video demonstrates practically how they differ.

这个YouTube视频展示了他们的不同之处。

But now for a long textual answer.

但现在我们来看一个长篇大论的答案。

When we talk about .NET there are two different things one there is .NET framework and the other there are languages ( C# , VB.NET etc) which use that framework.

当我们讨论。net时,有两种不同的东西,一种是。net框架,另一种是语言(c#, VB)使用那个框架的。

c#中字符串和字符串的区别是什么?

"System.String" a.k.a "String" ( capital "S") is a .NET framework data type while "string" is a C# data type.

”系统。“a.k.字符串。“String”(大写“S”)是。net框架数据类型,而“String”是c#数据类型。

c#中字符串和字符串的区别是什么?

In short "String" is an alias ( the same thing called with different names) of "string". So technically both the below code statements will give the same output.

简而言之,“String”是“String”的别名(用不同名称调用的同一事物)。因此,技术上来说,下面的代码语句将给出相同的输出。

String s = "I am String";

or

string s = "I am String";

In the same way there are aliases for other c# data type as shown below:-

同样的,还有其他c#数据类型的别名,如下所示:-

object: System.Object, string: System.String, bool: System.Boolean, byte: System.Byte, sbyte: System.SByte, short: System.Int16 and so on

对象:系统。字符串对象:系统。字符串,bool:系统。布尔,字节:系统。字节,sbyte:系统。SByte短:系统。Int16等等

Now the million dollar question from programmer's point of view So when to use "String" and "string"?

现在从程序员的角度来看这个百万美元的问题那么什么时候使用"String"和"String"呢?

First thing to avoid confusion use one of them consistently. But from best practices perspective when you do variable declaration it's good to use "string" ( small "s") and when you are using it as a class name then "String" ( capital "S") is preferred.

避免混淆的第一件事就是始终使用其中之一。但是,从最佳实践的角度来看,当您进行变量声明时,最好使用“string”(小写的“s”),当您将它用作类名时,最好使用“string”(大写的“s”)。

In the below code the left hand side is a variable declaration and it declared using "string". At the right hand side we are calling a method so "String" is more sensible.

在下面的代码中,左边是一个变量声明,它使用“string”声明。在右边,我们调用一个方法,因此“String”更合理。

string s = String.ToUpper() ;

#13


127  

string is just an alias for System.String. The compiler will treat them identically.

string只是System.String的别名。编译器会对它们一视同仁。

The only practical difference is the syntax highlighting as you mention, and that you have to write using System if you use String.

惟一的实际区别是语法突出显示,正如您所提到的,如果使用字符串,则必须使用System编写。

#14


120  

Lower case string is an alias for System.String. They are the same in C#.

小写字符串是System.String的别名。它们在c#中是一样的。

There's a debate over whether you should use the System types (System.Int32, System.String, etc.) types or the C# aliases (int, string, etc). I personally believe you should use the C# aliases, but that's just my personal preference.

关于是否应该使用系统类型(System)存在争论。Int32,系统。类型或c#别名(int, String,等等)。我个人认为你应该使用c#别名,但这只是我个人的偏好。

#15


113  

Both are same. But from coding guidelines perspective it's better to use string instead of String. This is what generally developers use. e.g. instead of using Int32 we use int as int is alias to Int32

两者都是相同的。但是从编码指南的角度来看,最好使用字符串而不是字符串。这是开发人员通常使用的。我们用int代替Int32,因为int是Int32的别名

FYI “The keyword string is simply an alias for the predefined class System.String.” - C# Language Specification 4.2.3 http://msdn2.microsoft.com/En-US/library/aa691153.aspx

关键字字符串只是预定义类System.String的别名。- c#语言规范4.2.3 http://msdn2.microsoft.com/En-US/library/aa691153.aspx

#16


96  

As the others are saying, they're the same. StyleCop rules, by default, will enforce you to use string as a C# code style best practice, except when referencing System.String static functions, such as String.Format, String.Join, String.Concat, etc...

正如其他人所说,他们是一样的。默认情况下,StyleCop规则将强制您使用string作为c#代码样式的最佳实践,除非引用系统。字符串静态函数,如字符串。格式字符串。加入,字符串。Concat等等……

#17


78  

Using System types makes it easier to port between C# and VB.Net, if you are into that sort of thing.

使用系统类型可以更容易地在c#和VB之间移植。Net,如果你喜欢这种东西。

#18


73  

Against what seems to be common practice among other programmers, I prefer String over string, just to highlight the fact that String is a reference type, as Jon Skeet mentioned.

与其他程序员常见的做法相反,我更喜欢字符串而不是字符串,只是强调一下,正如Jon Skeet所提到的,字符串是一种引用类型。

#19


68  

string is an alias (or shorthand) of System.String. That means, by typing string we meant System.String. You can read more in think link: 'string' is an alias/shorthand of System.String.

string是System.String的别名(或简写)。这意味着,通过输入string我们意味着System.String。您可以在think link中阅读更多内容:“string”是System.String的别名/简写。

#20


61  

String (System.String) is a class in the base class library. string (lower case) is a reserved work in C# that is an alias for System.String. Int32 vs int is a similar situation as is Boolean vs. bool. These C# language specific keywords enable you to declare primitives in a style similar to C.

String (System.String)是基类库中的一个类。string(小写)是c#中的保留工作,是System.String的别名。Int32 vs int与Boolean与bool的情况类似。这些c#语言特定的关键字使您能够以类似于C的样式声明原语。

#21


54  

String is not a keyword and it can be used as Identifier whereas string is a keyword and cannot be used as Identifier. And in function point of view both are same.

String不是关键字,它可以用作标识符,而String是关键字,不能用作标识符。从功能的角度来看,两者都是一样的。

#22


54  

Coming late to the party: I use the CLR types 100% of the time (well, except if forced to use the C# type, but I don't remember when the last time that was).

聚会迟到:我100%使用CLR类型(除了*使用c#类型,但我不记得上次是什么时候)。

I originally started doing this years ago, as per the CLR books by Ritchie. It made sense to me that all CLR languages ultimately have to be able to support the set of CLR types, so using the CLR types yourself provided clearer, and possibly more "reusable" code.

我最初是在几年前开始做这件事的,根据里奇的CLR书籍。对我来说,所有CLR语言最终都必须能够支持CLR类型的集合是有意义的,因此使用CLR类型本身可以提供更清晰、可能更“可重用”的代码。

Now that I've been doing it for years, it's a habit and I like the coloration that VS shows for the CLR types.

现在我已经做了好几年了,这是一种习惯,我喜欢VS为CLR类型显示的颜色。

The only real downer is that auto-complete uses the C# type, so I end up re-typing automatically generated types to specify the CLR type instead.

唯一令人沮丧的是,自动补全使用c#类型,因此我最终重新输入自动生成的类型来指定CLR类型。

Also, now, when I see "int" or "string", it just looks really wrong to me, like I'm looking at 1970's C code.

而且,现在,当我看到int或者string时,我觉得它看起来很不对,就像我在看1970年的C代码。

#23


47  

I'd just like to add this to lfousts answer, from Ritchers book:

我想补充一下lfousts的回答,来自Ritchers的书:

The C# language specification states, “As a matter of style, use of the keyword is favored over use of the complete system type name.” I disagree with the language specification; I prefer to use the FCL type names and completely avoid the primitive type names. In fact, I wish that compilers didn’t even offer the primitive type names and forced developers to use the FCL type names instead. Here are my reasons:

c#语言规范说,“就风格而言,使用关键字比使用完整的系统类型名更受欢迎。”“我不同意语言规范;我更喜欢使用FCL类型名,并完全避免使用原始类型名。事实上,我希望编译器甚至不提供原始类型名称,并强迫开发人员使用FCL类型名称。下面是我的理由:

I didn't get his opinion before I read the complete paragraph.

在我读完整段之前,我没有得到他的意见。

#24


41  

It's a matter of convention, really. "string" just looks more like C/C++ style. The general convention is to use whatever shortcuts your chosen language has provided (int/Int for Int32). This goes for "object" and "decimal" as well.

这是一个惯例,真的。“string”看起来更像C/ c++风格。一般约定是使用您所选择的语言提供的任何快捷方式(int/ int为Int32)。这也适用于“对象”和“十进制”。

Theoretically this could help to port code into some future 64-bit standard in which "int" might mean Int64, but that's not the point, and I would expect any upgrade wizard to change any "int" references to "Int32" anyway just to be safe.

理论上,这有助于将代码移植到未来的64位标准中,其中“int”可能表示Int64,但这不是重点,我希望任何升级向导都能将任何“int”引用修改为“Int32”,以确保安全。

#25


40  

There is no difference.

没有区别。

The C# keyword string maps to the .NET type System.String - it is an alias that keeps to the naming conventions of the language.

c#关键字字符串映射到。net类型系统。字符串——它是一个别名,保留了语言的命名约定。

Similarly, int maps to System.Int32.

同样,int映射到System.Int32。

#26


39  

New answer after 6 years and 5 months (procrastination).

6年5个月后的新答案(拖延症)。

While string is a reserved C# keyword that always has a fixed meaning, String is just an ordinary identifier which could refer to anything. Depending on members of the current type, the current namespace and the applied using directives and their placement, String could be a value or a type distinct from global::System.String.

string是一个保留的c#关键字,总是有固定的含义,string只是一个普通的标识符,可以指向任何东西。根据当前类型的成员、当前名称空间和应用的使用指令及其位置,字符串可以是值或类型,与global: System.String不同。

I shall provide two examples where using directives will not help.

我将提供两个使用指示不会有帮助的示例。


First, when String is a value of the current type (or a local variable):

首先,当字符串是当前类型(或局部变量)的值时:

class MySequence<TElement>
{
  public IEnumerable<TElement> String { get; set; }

  void Example()
  {
    var test = String.Format("Hello {0}.", DateTime.Today.DayOfWeek);
  }
}

The above will not compile because IEnumerable<> does not have a non-static member called Format, and no extension methods apply. In the above case, it may still be possible to use String in other contexts where a type is the only possibility syntactically. For example String local = "Hi mum!"; could be OK (depending on namespace and using directives).

上面的内容不会编译,因为IEnumerable<>没有一个非静态成员称为格式,也不应用扩展方法。在上述情况下,可能仍然可以在其他情况下使用字符串,其中类型是惟一可能的语法。例如字符串local =“Hi mum!”;可能没问题(取决于命名空间和使用指令)。

Worse: Saying String.Concat(someSequence) will likely (depending on usings) go to the Linq extension method Enumerable.Concat. It will not go to the static method string.Concat.

更糟的是:说String.Concat(someSequence)可能(取决于使用情况)转到Linq扩展方法Enumerable.Concat。它不会进入静态方法。


Secondly, when String is another type, nested inside the current type:

其次,当字符串是另一种类型时,嵌套在当前类型中:

class MyPiano
{
  protected class String
  {
  }

  void Example()
  {
    var test1 = String.Format("Hello {0}.", DateTime.Today.DayOfWeek);
    String test2 = "Goodbye";
  }
}

Neither statement in the Example method compiles. Here String is always a piano string, MyPiano.String. No member (static or not) Format exists on it (or is inherited from its base class). And the value "Goodbye" cannot be converted into it.

示例方法中的任何语句都不会编译。这里的弦总是钢琴弦,我的钢琴弦。它上不存在任何成员(静态或非静态)格式(或从基类继承)。“再见”的值不能转换成它。

#27


34  

string is a keyword, and you can't use string as an identifier.

字符串是关键字,不能使用字符串作为标识符。

String is not a keyword, and you can use it as an identifier:

String不是关键字,您可以将它用作标识符:

Example

例子

string String = "I am a string";

The keyword string is an alias for System.String aside from the keyword issue, the two are exactly equivalent.

关键字字符串是系统的别名。除了关键字问题之外,这两者是完全等价的。

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

#28


34  

There's a quote on this issue from Daniel Solis' book.

在丹尼尔·索利斯的书中有这样一段话。

All the predefined types are mapped directly to underlying .NET types. The C# type names (string) are simply aliases for the .NET types (String or System.String), so using the .NET names works fine syntactically, although this is discouraged. Within a C# program, you should use the C# names rather than the .NET names.

所有预定义类型都直接映射到底层的。net类型。c#类型名称(string)只是. net类型(string或System.String)的别名,因此使用. net名称在语法上很有用,尽管不建议这样做。在c#程序中,您应该使用c#名称而不是。net名称。

#29


33  

Yes, that's no difference between them, just like the bool and Boolean.

是的,它们之间没有区别,就像布尔和布尔一样。

#30


30  

There is no difference between the two - string, however, appears to be the preferred option when considering other developers' source code.

然而,在考虑其他开发人员的源代码时,这两个字符串似乎是首选的选项。