在C#中,类和结构是用来创建类实例的蓝图。结构用于轻量级对象,如颜色、矩形、点等。
与类不同,C#中的结构是值类型,而不是引用类型。如果您有在创建Struct之后不打算修改的数据,则它很有用。
让无涯教程看一个简单的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("Area of Rectangle is: " + (r.width * r.height)); } }
Area of Rectangle is: 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("Area of Rectangle is: "+(width*height)); } } public class TestStructs { public static void Main() { Rectangle r = new Rectangle(5, 6); r.areaOfRectangle(); } }
Area of Rectangle is: 30
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)