C# 支持 struct 关键字,它也是一个起源于 C 但在 Java 中不可用的项。可以将 struct 想像为一个轻量类。像类一样,它可以包含构造函数、常量、字段、方法、属性、索引器、运算符和嵌套类型。structs 与类不同的是,它们不能是抽象的,并且不支持实现继承。与类的重要区别在于,structs 是值类型,而类是引用类型。对于 structs,构造函数的工作方式有一些差异。尤其是,编译器始终提供一个默认的无参数构造函数,它是不允许替换的。
在下面的示例中,用 new 关键字初始化 struct(调用默认的无参数构造函数),然后设置实例的成员。
public struct Customer
{
public int ID;
public string Name;
public Customer(int customerID, string customerName)
{
ID = customerID;
Name = customerName;
}
}
class TestCustomer
{
static void Main()
{
Customer c1 = new Customer(); //using the default constructor
System.Console.WriteLine("Struct values before initialization:");
System.Console.WriteLine("ID = {0}, Name = {1}", c1.ID, c1.Name);
System.Console.WriteLine();
c1.ID = 100;
c1.Name = "Robert";
System.Console.WriteLine("Struct values after initialization:");
System.Console.WriteLine("ID = {0}, Name = {1}", c1.ID, c1.Name);
}
}
编译和运行上述代码时,其输出结果显示 struct 变量已按默认值初始化.int变量初始化为 0,string 变量初始化为空字符串:
Struct values before initialization:
ID = 0, Name =
如果 Customer 声明为 class 而不是 struct,则不会提供无参数的构造函数,并且下面的代码行会导致编译错误:
Customer c1 = new Customer(); //using the default constructor