C# 关于反射的简单示例

写在前面

在日常开发中,我们经常使用反射来动态获取关于类的信息,或者是动态给类实例成员赋值;反射提供了封装程序集、模块和类型的对象(Type 类型)。可以使用反射动态创建类型的实例,将类型绑定到现有对象,或从现有对象获取类型并调用其方法或访问其字段和属性。如果代码中使用了属性,可以利用反射对它们进行访问。

代码实现

cs 复制代码
using System.Reflection;

class ReflectionDemo
{

    static void Main(string[] args)
    {

        Assembly myAssembly = Assembly.Load("ReflectionDemo");

        var types = myAssembly.GetTypes();//获取类型
        foreach (Type type in types)//针对每个类型获取详细信息
        {
            if (type.Name != "MyClass") continue;

            Console.WriteLine($"type name:{type.Name}");
            Console.WriteLine($"is interface:{type.IsInterface}"); 

            //获取类型的结构信息
            var myConstructors = type.GetConstructors();
            Console.WriteLine($"constructor count: {myConstructors.Length}");

            //获取类型的字段信息
            var myFields = type.GetFields();
            Console.WriteLine($"field count: {myFields.Length}");

            //获取方法信息
            var myMethodInfo = type.GetMethods();
            Console.WriteLine($"method count: {myMethodInfo.Length}");

            //获取属性信息
            var myProperties = type.GetProperties();
            Console.WriteLine($"property count: {myProperties.Length}");

            //获取事件信息
            var myEvents = type.GetEvents();
            Console.WriteLine($"event count: {myEvents.Length}");
        }
 
        var myClass = myAssembly.CreateInstance("MyClass", true, BindingFlags.Default, null, new object[] { "test" }, null, null);
        if (myClass != null)
        {
            var myClassType = myClass.GetType();
            var ageProp = myClassType.GetProperty("Age");
            ageProp.SetValue(myClass, 100);
            Console.WriteLine($"Age is:{((MyClass)myClass).Age }");
        }

        Console.ReadLine();
    }

}

public class MyClass
{

    public int Type = 0;

    public MyClass()
    {

    }

    public MyClass(string name)
    {
        Name = name;
    }

    public delegate void HandleEvent(string eventName);

    public event HandleEvent MyEvent;

    public int Id { get; set; }

    public string Name { get; set; }

    public int Age { get; set; }

    public int GetAge()
    {
        return Age;
    }

    public string GetFullName()
    {
        return $"MyClass.{Name}";
    }


}

调用示例

相关推荐
globaldomain14 小时前
什么是用于长距离高速传输的TCP窗口扩展?
开发语言·网络·php
沈阳信息学奥赛培训14 小时前
#undef 指令 (C/C++)
c语言·开发语言·c++
2401_8732046514 小时前
分布式系统安全通信
开发语言·c++·算法
Dxy123931021615 小时前
JS发送请求的方法详解
开发语言·javascript·ecmascript
sw12138916 小时前
C++中的代理模式实战
开发语言·c++·算法
難釋懷16 小时前
Lua语法入门-条件控制、函数
开发语言·junit·lua
桌面运维家16 小时前
Win10打印机共享故障排查:权限与网络配置详解
开发语言·网络·php
Sunshine for you17 小时前
实时操作系统中的C++
开发语言·c++·算法
史蒂芬_丁17 小时前
C++深度拷贝例子
java·开发语言·c++
Knight_AL17 小时前
Nacos 启动问题 Failed to create database ’D:\nacos\nacos\data\derby-data’
开发语言·数据库·python