阿宽

Nothing is more powerful than habit!
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

泛型方法的定义

Posted on 2010-09-08 22:40  宽田  阅读(446)  评论(0编辑  收藏  举报

 泛型方法定义如下。

 

    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();
        }
    }