首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 反射核心:typeof 與 GetType() 運算子深度解析

     編輯:關於C語言

typeof vs GetType()

  • typeof:編譯期運算子,回傳 System.Type 物件
  • GetType():執行期方法,回傳物件實際執行型別

兩者皆可搭配反射動態查詢物件資訊。

範例:列舉類別成員與方法

using System;
using System.Reflection;

public class Customer
{
    string name;
    public string Name
    {
        set { name = value; }
        get { return name; }
    }
}

public class TypeTest
{
    public static void Main()
    {
        Type typeObj = typeof(Customer);
        Console.WriteLine("The Class name is {0}", typeObj.FullName);

        Console.WriteLine("\nThe Class Members\n=================\n");
        MemberInfo[] members = typeObj.GetMembers();
        foreach (MemberInfo m in members)
            Console.WriteLine(m.ToString());

        Console.WriteLine("\nThe Class Methods\n=================\n");
        MethodInfo[] methods = typeObj.GetMethods();
        foreach (MethodInfo m in methods)
            Console.WriteLine(m.ToString());
    }
}

輸出:

The Class name is Customer
The Class Members
=================
Int32 GetHashCode()
Boolean Equals(System.Object)
System.String ToString()
Void set_Name(System.String)
System.String get_Name()
System.Type GetType()
Void .ctor()
System.String Name
The Class Methods
=================
Int32 GetHashCode()
Boolean Equals(System.Object)
System.String ToString()
Void set_Name(System.String)
System.String get_Name()
System.Type GetType()

可見 C# 內部將屬性存取器轉為 get_xxx()/set_xxx() 方法,並繼承 System.Object 成員。

範例:執行期判斷運算式型別

using System;

public class TypeTest
{
    public static void Main()
    {
        int radius = 8;
        Console.WriteLine("Calculated area is = {0}", radius * radius * System.Math.PI);
        Console.WriteLine("The result is of type {0}", (radius * radius * System.Math.PI).GetType());
    }
}

輸出:

Calculated area is = 201.061929829747
The result is of type System.Double

因 Math.PI 為 double,整個運算結果提升為 double。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved