C#的元数据和反射

反射和new是一个相对的概念
new 是在编译的时候创建一个类的实例对象,这个要提前知道
反射不需要提前知道,反射更适合用在通用模块上

反射:获得类的一些元数据信息

复制代码
using System;
using System.Reflection;

class Program
{
    static void Main()
    {
        Type type = typeof(Person); // 获取类型
        Console.WriteLine("类名: " + type.Name);
        Console.WriteLine("命名空间: " + type.Namespace);

        Console.WriteLine("属性列表:");
        foreach (PropertyInfo prop in type.GetProperties())
        {
            Console.WriteLine(prop.Name + " - " + prop.PropertyType);
        }
    }
}

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

//输出
类名: Person
命名空间:
属性列表:
Name - System.String
Age - System.Int32

复制代码

 

复制代码
//调用实例方法
using System;
using System.Reflection;

class Person
{
    public void SayHello(string name)
    {
        Console.WriteLine($"Hello, {name}!");
    }
}

class Program
{
    static void Main()
    {
        // 1. 获取类型
        Type type = typeof(Person);

        // 2. 创建实例
        object instance = Activator.CreateInstance(type);

        // 3. 获取方法信息
        MethodInfo method = type.GetMethod("SayHello");

        // 4. 调用方法
        method.Invoke(instance, new object[] { "Tom" });
    }
}

 

复制代码

 

复制代码
class Utility
{
    public static void PrintMessage(string message)
    {
        Console.WriteLine("Message: " + message);
    }
}

class Program
{
    static void Main()
    {
        Type type = typeof(Utility);
        MethodInfo method = type.GetMethod("PrintMessage");

        // 调用静态方法,不需要实例
        method.Invoke(null, new object[] { "Hello, World!" });
    }
}
复制代码

 

复制代码
特性
定义特性
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class MyCustomAttribute : Attribute
{
    public string Description { get; }

    public MyCustomAttribute(string description)
    {
        Description = description;
    }
}
使用特性
[MyCustomAttribute("这是一个测试类")]
public class TestClass
{
    [MyCustomAttribute("这是一个测试方法")]
    public void TestMethod() { }
}
读取特性
Type type = typeof(TestClass);
object[] attributes = type.GetCustomAttributes(typeof(MyCustomAttribute), false);

foreach (MyCustomAttribute attr in attributes)
{
    Console.WriteLine("特性描述: " + attr.Description);
}

特性和反射结合
MethodInfo method = typeof(TestClass).GetMethod("TestMethod");
var attributes = method.GetCustomAttributes(typeof(MyCustomAttribute), false);

foreach (MyCustomAttribute attr in attributes)
{
    Console.WriteLine("方法上的特性描述: " + attr.Description);
}
复制代码

 


 

posted @   爱晒太阳的懒猫。。  阅读(9)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示