C#高级程序设计Type类

Posted teayear

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C#高级程序设计Type类相关的知识,希望对你有一定的参考价值。

C#高级程序设计

一.反射

是.net一种非常重要的机制,通过反射可以在运行时获取类的成员、属性、事件和构造方法等等。有了反射,使我们对类的类型了如指掌。

二.涉及的类

2.1 Type类

System.Reflection命名空间下。

查阅相应的帮助文档。

Name

NameSpace

方法比较多:

可以获取字段

可以获取方法

MethodInfo []mi=t.GetMethods();

System.String get_Id()
Void set_Id(System.String)

System.String get_Name()
Void set_Name(System.String)

Boolean Equals(System.Object)
Int32 GetHashCode()
System.Type GetType()
System.String ToString()

可以获取构造方法

反射功能非常强大!!!

参考代码:

Student.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace demo01

    class Student
    
        string id;
       public  string name;
        //属性:
        public string Name
        
            get  return name; 
            set  name = value; 
        

        public string Id
        
            get  return id; 
            set  id = value; 
        

        public Student()  
        public Student(string name) 
            this.name = name;
        
    


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//引用反射命名空间;
using System.Reflection;

namespace demo01

    class Program
    
        static void Main(string[] args)
        
            //构造这个Student类
            //Student stu = new Student();


            //Type t = stu.GetType();//Type是抽象类,不能被直接new

            //动态获取类的信息 ;
            //我们可以向GetType()方法里面传递参数;获取该类的信息 ;
            Type t = Type.GetType("demo01.Student");
            Console.WriteLine(t.Name);
            Console.WriteLine(t.Namespace);
            Console.WriteLine(t.ReflectedType); //获取该成员的类对象,没有输出;
            Console.WriteLine(t);  //Type对象t:完全限定名;命名空间+类名

            //方法
            FieldInfo[] fi=t.GetFields();
            foreach (FieldInfo item in fi)
                Console.WriteLine(item);
            //发现没有任何输出???只能出来public的类型字段;

            MethodInfo []mi=t.GetMethods();
            foreach (MethodInfo item in mi)
                Console.WriteLine(item);
            //获取构造方法
            ConstructorInfo []ci=t.GetConstructors();
            foreach (ConstructorInfo item in ci)
                Console.WriteLine(item);

            Console.Read();
        
    


三.IL DASM反编译工具

​ 微软的IL反编译工具(ildasm.exe)有所认识。我最早接触到这工具是公司同事使用他反编译exe程序,进行研读和修改。感觉他还是很强大。
  IL是微软平台上的一门中间语言,我们常写的C#代码在编译器中都会自动转换成IL,然后在由即时编译器(JIT Compiler)转化机器码,最后被CPU执行。ildasm.exe反编译工具将IL汇编成可跨平台可执行的(pe)文件。可供我们了解别人代码和修改。有了他我们看待问题可以不用停留在编辑器层面,可深入中间层。

3.1 寻找路径

C:\\Program Files (x86)\\Microsoft SDKs\\Windows\\v8.0A\\bin\\NETFX 4.0 Tools

3.2 找到你的exe的路径

我们的在这里: D:\\zyg\\rb\\demo01\\demo01\\bin\\Debug

3.3 使用IL DASM工具打开

以上是关于C#高级程序设计Type类的主要内容,如果未能解决你的问题,请参考以下文章

Java基础10—类的高级特性

Java基础10—类的高级特性

C# 自定义控件无法查看视图设计:文件中的类都不能进行设计,因此未能为该文件显示设计器

Java高级部分--工具类

C# vs Python: 语言特性Conda和Jupyter Notebook环境

c# 反射时GetType方法查找Type的分析