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

 

转载于:https://www.cnblogs.com/FHL007/p/11113610.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C#中的反射是指在运行时动态地获取类型信息、访问属性和调用方法的能力。通过反射,我们可以在运行时检查类型信息、创建实例调用方法、访问属性和字段等。使用反射可以实现一些动态的操作,比如在不知道类型的情况下调用方法或者访问其属性。 要使用反射获取类型信息和调用方法,可以按照以下步骤进行: 1. 获取类型信息:使用`Type`类可以获取类型的信息,比如获取类型的名称、方法、属性等。可以使用`typeof`关键字获取已知类型的信息,也可以使用`GetType()`方法获取对象的类型信息。 2. 创建实例:使用反射可以动态创建类型的实例,可以使用`Activator.CreateInstance`方法来创建对象。 3. 调用方法:使用`MethodInfo`类可以获取方法的信息,然后使用`Invoke`方法调用方法。 下面是一个简单的示例,演示如何使用反射获取类型信息和调用方法: ```csharp using System; using System.Reflection; public class MyClass { public void MyMethod() { Console.WriteLine("Hello from MyMethod!"); } } public class Program { public static void Main() { Type type = typeof(MyClass); object instance = Activator.CreateInstance(type); MethodInfo methodInfo = type.GetMethod("MyMethod"); methodInfo.Invoke(instance, null); } } ``` 在上面的示例中,我们首先获取`MyClass`的类型信息,然后使用`Activator.CreateInstance`创建了一个`MyClass`的实例。接着,我们获取了`MyMethod`方法的信息,并使用`Invoke`方法调用了该方法

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值