简体   繁体   English

C#.Net不区分大小写的字符串

[英]C#.Net case-insensitive string

Why does C#.Net allow the declaration of the string object to be case-insensitive? 为什么C#.Net允许字符串对象的声明不区分大小写?

String sHello = "Hello";
string sHello = "Hello";

Both the lower-case and upper-case S of the word String are acceptable and this seems to be the only object that allows this. 单词String的小写和大写S都是可以接受的,并且这似乎是唯一允许这样做的对象。

Can anyone explain why? 谁能解释为什么?

string is a language keyword while System.String is the type it aliases. string是语言关键字,而System.String是它的别名类型。

Both compile to exactly the same thing, similarly: 两者都编译为完全相同的东西,类似地:

  • int is System.Int32 intSystem.Int32
  • long is System.Int64 longSystem.Int64
  • float is System.Single floatSystem.Single
  • double is System.Double doubleSystem.Double
  • char is System.Char charSystem.Char
  • byte is System.Byte byteSystem.Byte
  • short is System.Int16 shortSystem.Int16
  • ushort is System.UInt16 ushortSystem.UInt16
  • uint is System.UInt32 uintSystem.UInt32
  • ulong is System.UInt64 ulongSystem.UInt64

I think in most cases this is about code legibility - all the basic system value types have aliases, I think the lower case string might just be for consistency. 我认为在大多数情况下,这与代码的可读性有关-所有基本系统值类型都具有别名,我认为小写的string可能只是为了保持一致性。

Further to the other answers, it's good practice to use keywords if they exist. 除其他答案外,最好使用关键词(如果存在)。

Eg you should use string rather than System.String . 例如,您应该使用string而不是System.String

"String" is the name of the class. “字符串”是类的名称。 "string" is keyword that maps this class. “字符串”是映射此类的关键字。

it's the same like 就像一样

  • Int32 => int Int32 =>整数
  • Decimal => decimal 小数=>小数
  • Int64 => long Int64 =>长

... and so on... ... 等等...

"string" is a C# keyword. “字符串”是C#关键字。 it's just an alias for "System.String" - one of the .NET BCL classes. 它只是.NET BCL类之一“ System.String”的别名。

“字符串”只是系统命名空间中类“字符串”的C#别名。

I use String and not string, Int32 instead of int, so that my syntax highlighting picks up on a string as a Type and not a keyword. 我使用String而不是string,使用Int32而不是int,这样我的语法高亮显示了作为类型而不是关键字的字符串。 I want keywords to jump out at me. 我想让关键词跳出来。

string is an alias for System.String. string是System.String的别名。 They are the same thing. 他们是一样的东西。

By convention, though, objects of type (System.String) are generally refered to as the alias - eg 但是,按照惯例,通常将类型(System.String)的对象称为别名-例如

string myString = "Hello";

whereas operations on the class use the uppercase version eg 而对类的操作使用大写版本,例如

String.IsNullOrEmpty(myStringVariable);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM