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
文章来源微信公众号
想要更快更方便的了解相关知识,可以关注微信公众号
****欢迎关注我的asp.net core系统课程****
《asp.net core精要讲解》 https://ke.qq.com/course/265696
《asp.net core 3.0》 https://ke.qq.com/course/437517
《asp.net core项目实战》 https://ke.qq.com/course/291868
《基于.net core微服务》 https://ke.qq.com/course/299524
《asp.net core精要讲解》 https://ke.qq.com/course/265696
《asp.net core 3.0》 https://ke.qq.com/course/437517
《asp.net core项目实战》 https://ke.qq.com/course/291868
《基于.net core微服务》 https://ke.qq.com/course/299524
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需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