泛型方法定义如下。

 

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


 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-10-20
  • 2021-06-25
  • 2021-10-25
  • 2021-12-24
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-12-18
  • 2021-10-05
  • 2021-07-07
  • 2022-12-23
  • 2021-11-09
相关资源
相似解决方案