C# 實例的Gettype(),和類的typeof(),反射獲取類的對象,調用方法


都是為了獲取類的引用的數據類型System.Type。

1、GetType()方法繼承自Object,所以C#中任何對象都具有GetType()方法,x.GetType(),其中x為變量名

2、typeof(x)中的x,必須是具體的類名、類型名稱等,不可以是變量名稱

3、System.Type.GetType(),有兩個重載方法

比如有這樣一個變量i:
Int16 i = new Int16();

使用GetType(),i.GetType()返回值是Int16的類型,但是無法使用typeof(i),因為i是一個變量,

使用typeof(),則只能:typeof(Int32),返回的同樣是Int16的類型。

枚舉類的轉換,String——枚舉類,以串口中Parity為例

    objParity= (Parity)Enum.Parse(typeof(Parity), "9600");

獲取類的Type屬性,除了上面的使用實例獲取,或者typeof,還有一種提供類的完整信息字符串,根據類名來獲取Type

    //取得當前方法命名空間    
    str += "命名空間名:" + System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Namespace + "\n";

    //取得當前方法類全名 包括命名空間    
    str += "類名:" + System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName + "\n";

    //取得當前方法名    
    str += "方法名:" + System.Reflection.MethodBase.GetCurrentMethod().Name + "\n"; str += "\n";
  //取得當前方法類全名 包括命名空間  

string classname = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName; //得到的是 命名空間.類

Type type = Type.GetType(classname); // 通過類名獲取同名類
 object obj = System.Activator.CreateInstance(type); // 創建實例

連上- 通過方法名調用方法

 

   public  class Person   //類A,父類
    { 
 public string My()     //不帶參數,有返回
        {
            return "我是人類";
        }
 public virtual string num()   //不帶參數,有返回,虛方法子類測試
        {
            return "我人類沒有";
        }
        public void Myvoid()   //不帶參數,無返回
        { Console.WriteLine("無參測試:"+"  "+Myclass()); }

        public void Myvoid(string name)   //帶參數,無返回
        { Console.WriteLine("有參數測試:" +name) ; }

        public string Myvoid(string name,string name1)   //帶參數,有返回
        { Console.WriteLine("有參數帶返回測試:" + name + name1); return name + name1; }

        public virtual string Myclass()   //虛方法返回類名,子類測試
        { return System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName; }//得到的是 命名空間.類名,返回該類的  名字

}

 public class Student:Person
   {
  public override string Myclass()
        { return System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName; }//得到的是 命名空間.類名,返回該類的  名字


        public override string num()
        {
            return "我學生沒有";
        }

}

  private void Main()
{
//父類測試  
 Person objperson = new Person();//實例person類
         string classname = objperson.Myclass();
         Type type = Type.GetType(classname);      // 通過類名獲取類的type類型
            //Type type = objperson.GetType();      // 通過實例對象 獲取類的type類型
         object obj = System.Activator.CreateInstance(type);       // 創建實例

          string strMethod = "My";  //方法名字
          System.Reflection.MethodInfo method = type.GetMethod(strMethod, new Type[] { });      // 獲取方法信息
          object[] parameters = null;   //無參數
          string result = (string)method.Invoke(obj, parameters);     // 調用方法,無參數,有返回值
          Console.WriteLine("無參返回測試:" + "  " + result);

          strMethod = "num";  //方法名字
          method = type.GetMethod(strMethod, new Type[] { });      // 獲取方法信息
          parameters = null;   //無參數
          result = (string)method.Invoke(obj, parameters);     // 調用方法,無參數,無返回值
          Console.WriteLine("無參返回測試,虛方法:" + "  " + result);

          strMethod = "Myvoid";  //方法名字
          method = type.GetMethod(strMethod, new Type[] { });      // 獲取方法信息
          parameters = null;   //無參數
          method.Invoke(obj, parameters);     // 調用方法,無參數,無返回值

          strMethod = "Myvoid";  //方法名字
          method = type.GetMethod(strMethod, new Type[] {  typeof(string) });      // 獲取方法信息帶一個參數
          parameters = new object[] { "hello" };   //一個參數
          method.Invoke(obj, parameters);     // 調用方法,有參數,無返回值

          strMethod = "Myvoid";  //方法名字
          method = type.GetMethod(strMethod, new Type[] { typeof(string), typeof(string) });      // 獲取方法信息帶兩個參數
          parameters = new object[] { "hello", "你好" };    //兩個參數
          method.Invoke(obj, parameters);     // 調用方法,有參數,有返回值




//子類測試
 Person objstudent = new Student();//實例person類
            string classname = objstudent.Myclass();
            Type type = Type.GetType(classname);      // 通過類名獲取類的type類型
            //Type type = objstudent.GetType();      // 通過實例對象 獲取類的type類型
            object obj = System.Activator.CreateInstance(type);       // 創建實例

            string strMethod = "My";  //方法名字
            System.Reflection.MethodInfo method = type.GetMethod(strMethod, new Type[] { });      // 獲取方法信息
            object[] parameters = null;   //無參數
            string result = (string)method.Invoke(obj, parameters);     // 調用方法,無參數,有返回值
            Console.WriteLine("無參返回測試:" + "  " + result);

            strMethod = "num";  //方法名字
            method = type.GetMethod(strMethod, new Type[] { });      // 獲取方法信息
            parameters = null;   //無參數
            result = (string)method.Invoke(obj, parameters);     // 調用方法,無參數,無返回值
            Console.WriteLine("無參返回測試,虛方法:" + "  " + result);

            strMethod = "Myvoid";  //方法名字
            method = type.GetMethod(strMethod, new Type[] { });      // 獲取方法信息
            parameters = null;   //無參數
            method.Invoke(obj, parameters);     // 調用方法,無參數,無返回值

            strMethod = "Myvoid";  //方法名字
            method = type.GetMethod(strMethod, new Type[] { typeof(string) });      // 獲取方法信息帶一個參數
            parameters = new object[] { "hello" };   //一個參數
            method.Invoke(obj, parameters);     // 調用方法,有參數,無返回值

            strMethod = "Myvoid";  //方法名字
            method = type.GetMethod(strMethod, new Type[] { typeof(string), typeof(string) });      // 獲取方法信息帶兩個參數
            parameters = new object[] { "hello", "你好" };    //兩個參數
            method.Invoke(obj, parameters);     // 調用方法,有參數,有返回值

}

 結果顯示:

 

 

 

Object對象轉為實體類對象

 

private T ConvertObject<T>(object asObject) where T : new()
{
    //創建實體對象實例
    var t = Activator.CreateInstance<T>();
    if (asObject != null)
    {
        Type type = asObject.GetType();
        //遍歷實體對象屬性
        foreach (var info in typeof(T).GetProperties())
        {
            object obj = null;
            //取得object對象中此屬性的值
            var val = type.GetProperty(info.Name)?.GetValue(asObject);
            if (val != null)
            {
                //非泛型
                if (!info.PropertyType.IsGenericType)
                    obj = Convert.ChangeType(val, info.PropertyType);
                else//泛型Nullable<>
                {
                    Type genericTypeDefinition = info.PropertyType.GetGenericTypeDefinition();
                    if (genericTypeDefinition == typeof(Nullable<>))
                    {
                        obj = Convert.ChangeType(val, Nullable.GetUnderlyingType(info.PropertyType));
                    }
                    else
                    {
                        obj = Convert.ChangeType(val, info.PropertyType);
                    }
                }
                info.SetValue(t, obj, null);
            }
        }
    }
    return t;
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM