本示例演示结构的语法和用法。它还介绍了类与结构之间的重大差异
// struct1.cs
using System; struct SimpleStruct { private int xval; public int X { get { return xval; } set { if (value < 100) xval = value; } } public void DisplayX() { Console.WriteLine("The stored value is: {0}", xval); } } class TestClass { public static void Main() { SimpleStruct ss = new SimpleStruct(); ss.X = 5; ss.DisplayX(); } }
// struct2.cs
using System; class TheClass { public int x; } struct TheStruct { public int x; } class TestClass { public static void structtaker(TheStruct s) { s.x = 5; } public static void classtaker(TheClass c) { c.x = 5; } public static void Main() { TheStruct a = new TheStruct(); TheClass b = new TheClass(); a.x = 1; b.x = 1; structtaker(a); classtaker(b); Console.WriteLine("a.x = {0}", a.x); Console.WriteLine("b.x = {0}", b.x); } }