C# 中 new 关键字的用途是什么?
csharpprogrammingserver side programming更新于 2025/10/15 2:52:17
使用 new 关键字创建数组的实例 −
int [] a = new int[5];
new 运算符用于创建对象或实例化对象。本例中使用 new 为类创建了一个对象 −
示例
using System;
namespace CalculatorApplication {
class NumberManipulator {
public void swap(int x, int y) {
int temp;
temp = x; /* 保存 x 的值 */
x = y; /* 将 y 赋值给 x */
y = temp; /* 将 temp 赋值给 y */
}
static void Main(string[] args) {
NumberManipulator n = new NumberManipulator();
/* 局部变量定义 */
int a = 100;
int b = 200;
Console.WriteLine("交换前,a 的值:{0}",a);
Console.WriteLine("交换前,b 的值:{0}",b);
/* 调用函数交换值 */
n.swap(a, b);
Console.WriteLine("交换后,a 的值:{0}",a);
Console.WriteLine("交换后,b 的值:{0}",b);
Console.ReadLine();
}
}
}
输出
交换前,a 的值:100 交换前,b 的值:200 交换后,a 的值:100 交换后,b 的值:200

