AOT反射库-AOTReflection

  在AOT项目中,使用反射有一些问题,本程序包利用源生成器,按不同的维度,提前获取对应类型的元数据,从而达到平滑使用Reflection部分功能。

  项目:

  https://github.com/axzxs2001/AOTReflection

  nuget:

  https://www.nuget.org/packages?q=AOTReflection

  如下面代码,利用泛型的反射,以达到灵活,但在当发布成AOT时,会发现GetString的返回值为空(注意:本地调试会返回结果),本程序包会解决掉这个问题。

复制代码
string GetString<T>(T t)
{
    var sb = new StringBuilder();
    var pros = typeof(T)?.GetProperties();
    foreach (var pro in pros)
    {
        if (pro != null)
        {
            if (pro.PropertyType.IsArray)
            {
                var arr = pro.GetValue(t) as string[];
                sb.Append($"{pro?.Name}:{string.Join(",", arr)};");
            }
            else
            {
                sb.Append($"{pro?.Name}:{pro?.GetValue(t)};");
            }
        }
    }
    InvockMethod(t);
    return sb.ToString();
}

void InvockMethod<T>(T t)
{
    var method = typeof(T)?.GetMethod("Print");
    method?.Invoke(t, new object[] { "用反射调用Print" });
}
复制代码

  说明:本例都是基于MiniAPI的AOT模版来实现的。

AOTReflectionGenerator.Attribute

1、在AOT项目中,安装AOTReflectionGenerator.Attribute nuget包

2、在AOT项目中定义AOTReflectionAttribute

namespace AOTReflectionHelper.Attribute
{
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct)]
    public partial class AOTReflectionAttribute : System.Attribute
    {
    }
}

3、定义实体类时,把需要Reflection的类加上[AOTReflectionHelper.Attribute.AOTReflection]特性

复制代码
public class Parent
{
    public void Print(string content)
    {
        Console.WriteLine($"反射类型名:{GetType().Name},Print参数:{content}");
    }
}
[AOTReflectionHelper.Attribute.AOTReflection]
public struct Order //: Parent
{
    public string Name { get; set; }
    public int Age { get; set; }
    public DateTime Birthday { get; set; }
    public string[] Hobbies { get; set; }
}
[AOTReflectionHelper.Attribute.AOTReflection]
public class Person : Parent
{
    public string Name { get; set; }
    public int Age { get; set; }
    public DateTime Birthday { get; set; }
    public string[] Hobbies { get; set; }
}
复制代码

4、这时就可以按照泛型的方式来使用基本的反射功能了,如GetString(T t)方法

复制代码
app.MapGet("/testattribute", () =>
{
    var order = new Order { Name = "桂素伟", Age = 10, Birthday = DateTime.Now, Hobbies = new string[] { "足球", "代码" } };
    return GetString(order);

});
app.MapPost("/testattribute", (Person person) =>
{
    return GetString(person);
});
复制代码

  AOTReflectionGenerator.Interface

1、在AOT项目中,安装AOTReflectionGenerator.Interface nuget包

2、在ATO项目中定义接口IAOTReflection

  文章来源微信公众号

  想要更快更方便的了解相关知识,可以关注微信公众号 

posted @   刘靖凯  阅读(8)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 一文读懂知识蒸馏
· 终于写完轮子一部分:tcp代理 了,记录一下
历史上的今天:
2022-02-21 .net LTS3.1升5.0和LTS6.0隐蔽的坑
2022-02-21 应用内moniter
2017-02-21 数组,一维数组,二维数组,交错数组
点击右上角即可分享
微信分享提示