zoukankan      html  css  js  c++  java
  • C#创建自定义泛型举例

    用自定义泛型实现交换任意类型的两个变量。

     1 class Program
     2     {
     3         static void Main(string[] args)
     4         {
     5             int a = 10, b = 90;
     6             Console.WriteLine("Before swap: {0}, {1}", a, b);
     7             Swap<int>(ref a, ref b);
     8             Console.WriteLine("After swap: {0}, {1}", a, b);
     9             Console.WriteLine("---------------------");
    10 
    11             string s1 = "Hello", s2 = "World";
    12             Console.WriteLine("Before swap: {0}  {1}", s1, s2);
    13             Swap<string>(ref s1, ref s2);
    14             Console.WriteLine("After swap: {0}  {1}", s1, s2);
    15             Console.WriteLine("---------------------");
    16 
    17             bool b1 = true, b2 = false;
    18             Console.WriteLine("Before swap: {0} , {1}", b1, b2);
    19             Swap<bool>(ref b1, ref b2);
    20             Console.WriteLine("After swap: {0}  , {1}", b1, b2);
    21             Console.WriteLine("---------------------");
    22 
    23             DisplayBaseClass<int>();
    24             DisplayBaseClass<string>();
    25 
    26             Console.ReadLine();
    27         }
    28 
    29         static void Swap<T>(ref T a, ref T b)
    30         {
    31             Console.WriteLine("You sent the Swap() method a {0}", typeof(T));
    32             T temp;
    33             temp = a;
    34             a = b;
    35             b = temp;
    36         }
    37 
    38         static void DisplayBaseClass<T>()
    39         {
    40             Console.WriteLine("Base class of {0} is : {1}", typeof(T), typeof(T).BaseType);
    41         }

    注:引用自 《Por C# 2010 and the .NET 4 Platform》

  • 相关阅读:
    etcd+confd管理nginx
    k8s基础
    nginx配置总结
    Golang相关
    docker基础
    celery结合django使用配置
    常用算法
    python3和paramiko安装
    git使用总结
    Linux系统入门实操经验分享
  • 原文地址:https://www.cnblogs.com/zhnhelloworld/p/3044126.html
Copyright © 2011-2022 走看看