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


}

调用示例

相关推荐
唐青枫21 小时前
C#.NET 数据库开发提速秘籍:SqlSugar 实战详解
c#·.net
mudtools2 天前
.NET驾驭Word之力:理解Word对象模型核心 (Application, Document, Range)
c#·.net
侃侃_天下2 天前
最终的信号类
开发语言·c++·算法
echoarts2 天前
Rayon Rust中的数据并行库入门教程
开发语言·其他·算法·rust
Aomnitrix2 天前
知识管理新范式——cpolar+Wiki.js打造企业级分布式知识库
开发语言·javascript·分布式
大飞pkz2 天前
【设计模式】C#反射实现抽象工厂模式
设计模式·c#·抽象工厂模式·c#反射·c#反射实现抽象工厂模式
每天回答3个问题2 天前
UE5C++编译遇到MSB3073
开发语言·c++·ue5
伍哥的传说2 天前
Vite Plugin PWA – 零配置构建现代渐进式Web应用
开发语言·前端·javascript·web app·pwa·service worker·workbox
小莞尔2 天前
【51单片机】【protues仿真】 基于51单片机八路抢答器系统
c语言·开发语言·单片机·嵌入式硬件·51单片机
我是菜鸟0713号2 天前
Qt 中 OPC UA 通讯实战
开发语言·qt