C# GetType和typeof

2018-01-16 03:58 更新

C#GetType和typeof

C#中的所有类型都在运行时由System.Type的实例表示。

有两种基本方法来获取System.Type对象:

  • 在实例上调用GetType。
  • 对类型名称使用typeof运算符。

GetType 在运行时计算; typeof 在编译时被静态计算。

System.Type具有类型名称,程序集,基本类型等属性。


例子

例如:

using System; 

class Point { 
   public int X, Y; 
} 

class Main { 
   static void Main() {
        Point p = new Point(); 
        Console.WriteLine (p.GetType().Name); // Point 
        Console.WriteLine (typeof (Point).Name); // Point 
        Console.WriteLine (p.GetType() == typeof(Point)); // True 
        Console.WriteLine (p.X.GetType().Name); // Int32 
        Console.WriteLine (p.Y.GetType().FullName); // System.Int32
   } 
} 

例2

以下代码从var定义的变量获取类型。


using System; 

class Program { 
  static void Main(string[] args) { 
    var name = "www.w3cschool.cn"; 
    var age = 25; 
    var isRabbit = true; 

    Type nameType = name.GetType(); 
    Type ageType = age.GetType(); 
    Type isRabbitType = isRabbit.GetType(); 

    Console.WriteLine("name is type " + nameType.ToString()); 
    Console.WriteLine("age is type " + ageType.ToString()); 
    Console.WriteLine("isRabbit is type " + isRabbitType.ToString()); 
  } 
} 
以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号