在 C# 中,类和结构是用于创建类实例的蓝图。结构用于轻量级对象,例如颜色、矩形、点等。
与类不同,C# 中的结构是值类型而不是引用类型。如果您有在创建结构后不打算修改的数据,这很有用。
让我们看一个简单的 struct Rectangle 示例,它有两个数据成员 width 和 height。
using System; public struct Rectangle { public int width, height; } public class TestStructs { public static void Main() { Rectangle r = new Rectangle(); r.width = 4; r.height = 5; Console.WriteLine("矩形的面积为:" + (r.width * r.height)); } }
输出:
矩形的面积是:20
让我们看看另一个结构示例,我们使用构造函数来初始化数据和方法来计算矩形的面积。
using System; public struct Rectangle { public int width, height; public Rectangle(int w, int h) { width = w; height = h; } public void areaOfRectangle() { Console.WriteLine("矩形的面积为: "+(width*height)); } } public class TestStructs { public static void Main() { Rectangle r = new Rectangle(5, 6); r.areaOfRectangle(); } }
输出:
矩形的面积是:30