C#中String和string的区别

C#中String和string的区别

技术背景

在C#编程中,Stringstring 是两个常被提及的概念。System.String 是 .NET Framework 中的字符串类,而 string 是 C# 语言为 System.String 提供的别名。了解它们之间的区别有助于编写更规范、更易读的代码。

实现步骤

基本使用

在代码中,stringString 都可以用来声明字符串变量,它们在功能上是等价的。示例代码如下:

1
2
3
4
// 使用 string 声明变量
string str1 = "Hello, World!";
// 使用 String 声明变量
String str2 = "Hello, World!";

作为类名使用

当需要调用 System.String 类的静态方法时,通常使用 String。示例如下:

1
2
string str = "hello";
string upperStr = String.ToUpper(str);

核心代码

类型别名列表

C# 中除了 stringSystem.String 的别名外,还有其他一些类型别名,完整列表如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
bool:    System.Boolean
byte: System.Byte
char: System.Char
decimal: System.Decimal
double: System.Double
float: System.Single
int: System.Int32
long: System.Int64
nint: System.IntPtr
object: System.Object
sbyte: System.SByte
short: System.Int16
string: System.String
uint: System.UInt32
ulong: System.UInt64
ushort: System.UInt16

枚举底层类型指定

在指定枚举的底层类型时,必须使用别名。示例如下:

1
2
3
4
// 错误示例
public enum Foo : UInt32 {}
// 正确示例
public enum Bar : uint {}

最佳实践

  • 变量声明:在进行变量声明时,建议使用 string,这与 C# 语言的语法和惯例保持一致,代码更易读。
  • 类名使用:当需要调用 System.String 类的静态方法时,使用 String 会更清晰地表明是在调用类的方法。
  • 团队协作:团队内部应保持一致性,避免代码风格混乱。

常见问题

变量命名冲突

string 是 C# 的保留字,不能直接作为变量名使用。如果需要使用 string 作为变量名,可以使用 @ 作为前缀。示例如下:

1
2
3
4
// 编译错误
StringBuilder string = new StringBuilder();
// 编译通过
StringBuilder @string = new StringBuilder();

未使用 using System

如果使用 String 而没有提前使用 using System; 语句,代码将无法编译。

命名冲突导致的编译错误

由于 String 只是一个普通的标识符,可能会与当前类型的成员、当前命名空间或 using 指令中的其他类型或值发生冲突,导致编译错误。示例如下:

1
2
3
4
5
6
7
8
9
10
class MySequence<TElement>
{
public IEnumerable<TElement> String { get; set; }

void Example()
{
// 编译错误,IEnumerable<> 没有 Format 方法
var test = String.Format("Hello {0}.", DateTime.Today.DayOfWeek);
}
}

C#中String和string的区别
https://119291.xyz/posts/2025-05-07.difference-between-string-and-string-in-csharp/
作者
ww
发布于
2025年5月7日
许可协议