1 #region Generic structuer 2 public struct Point<T> 3 { 4 //Generic state date. 5 private T xPos; 6 private T yPos; 7 //Generic constructor. 8 public Point(T xVal, T yVal) 9 { 10 xPos = xVal; 11 yPos = yVal; 12 } 13 //Generic properties 14 public T X 15 { 16 get { return xPos; } 17 set { xPos = value; } 18 } 19 public T Y 20 { 21 get { return yPos; } 22 set { yPos = value; } 23 } 24 25 public override string ToString() 26 { 27 return string.Format("[{0} , {1}]",xPos,yPos); 28 } 29 //Reset fields to the default value of the type parameter 30 public void ResetPoint() 31 { 32 xPos = default(T); 33 yPos = default(T); 34 } 35 } 36 #endregion 37 38 class Program 39 { 40 static void Main(string[] args) 41 { 42 Point<int> p = new Point<int>(20, 20); 43 Console.WriteLine("p.ToString()={0}", p.ToString()); 44 p.ResetPoint(); 45 Console.WriteLine("p.ToString()={0}", p.ToString()); 46 Console.WriteLine("--------------------"); 47 48 Point<double> p2 = new Point<double>(2.34, 5.31); 49 Console.WriteLine("p2.ToString() = {0}", p2.ToString()); 50 p2.ResetPoint(); 51 Console.WriteLine("p2.ToString() = {0}", p2.ToString()); 52 53 Console.ReadLine(); 54 } 55 }
注:引用自 《Por C# 2010 and the .NET 4 Platform》