zoukankan      html  css  js  c++  java
  • C#创建自定义泛型结构和类

     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》

  • 相关阅读:
    解决运行vue项目的报错This relative module was not found:
    Iterator 迭代器
    Strategy 策略模式
    Observer 观察者
    工厂模式总结(简单工厂,工厂方法,抽象工厂)
    Abstract Factory 抽象工厂
    Factroy 简单工厂
    Singleton 多线程
    Singleton 单例模式
    设计模式总结
  • 原文地址:https://www.cnblogs.com/zhnhelloworld/p/3044245.html
Copyright © 2011-2022 走看看