泛型方法的定义

 泛型方法定义如下。

    public class Printer
    {
        
/*
         * 本例为泛型方法
         * T是泛型类实例所存储类型的占位符。在泛型类型的实例定义中,必需指定这个实例存储的实际类型。         * 
         
*/
        
public void Print<T>(T argument)
        {
            
if (typeof(T)==typeof(string))
            {
                Console.WriteLine(argument);
            }
            
else
            {
                Console.WriteLine(argument.ToString());
            }
        }
    }


 调用方法为:

    class Program
    {
        
static void Main(string[] args)
        {
            Printer print 
= new Printer();
            Console.WriteLine(
"String Type:");
            print.Print
<string>("Hello");
            Console.WriteLine(
"Int Type:");
            print.Print
<int>(100);

            Console.ReadKey();
        }
    }


原文地址:https://www.cnblogs.com/scottckt/p/1821817.html