ToB企服应用市场:ToB评测及商务社交产业平台

标题: C# 12 拦截器 Interceptors [打印本页]

作者: 汕尾海湾    时间: 2024-5-14 19:03
标题: C# 12 拦截器 Interceptors
拦截器Interceptors是一种可以在编译时以声明方式更换原有应用的方法。
这种更换是通过让Interceptors声明它拦截的调用的源位置来实现的。
您可以利用拦截器作为源天生器的一部门进行修改,而不是向现有源编译添加代码。
 
演示

利用 .NET 8 创建一个控制台应用步伐。并在PropertyGroup中添加以下配置.。须要将其中WebApplication6更换为自己的定名空间。
  1. <InterceptorsPreviewNamespaces>$(InterceptorsPreviewNamespaces);WebApplication6</InterceptorsPreviewNamespaces>
复制代码
然后在单独的文件中创建InterceptsLocationAttribute。其定名空间必须是System.Runtime.CompilerServices,而不是应用步伐的定名空间。
  1. namespace System.Runtime.CompilerServices
  2. {
  3.     [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
  4.     public sealed class InterceptsLocationAttribute(string filePath, int line, int character) : Attribute
  5.     {
  6.     }
  7. }
复制代码
该属性包罗三个参数。
接着来创建一个具有三种方法的类,模拟新增/查询用户作为示例:
  1. public class GetUserService
  2. {
  3.     // This method will not be intercepted;
  4.     public void GetUserName()
  5.     {
  6.         Console.WriteLine("GetUserName");
  7.     }
  8.     // This method will be intercepted;
  9.     public void AddUser()
  10.     {
  11.         Console.WriteLine("AddUser");
  12.     }
  13.     // This method will not be intercepted;
  14.     public void DeleteUser()
  15.     {
  16.         Console.WriteLine("DeleteUser");
  17.     }
  18. }
复制代码
在 Program.cs 文件中,我创建了此类的一个实例,并创建了对这三个方法中每一个的调用。输出如下所示:
  1. var userService = new GetUserService();
  2. userService.GetUserName();
  3. userService.AddUser();
  4. userService.DeleteUser();
复制代码
现在让我们创建拦截类。该类必须遵循以下规则:
 
  1. using System.Runtime.CompilerServices;
  2. namespace WebApplication6
  3. {
  4.     public static class InterceptUserService
  5.     {
  6.         [InterceptsLocation(
  7.     filePath: @"D:\demo\test\ConsoleApp1\WebApplication6\Program.cs",
  8.     line: 14,
  9.     character: 25)]
  10.         public static void InterceptMethodAddUser(this GetUserService example)
  11.         {
  12.             Console.WriteLine("Interceptor is here!");
  13.         }
  14.     }
  15. }
复制代码
在此示例中,将拦截AddUser方法,并且将执行InterceptMethodAddUser方法,而不是执行方法AddUser。
filePath可以按以下方式获取

 
行号和字符号可以按以下方式获取

 
现在运行代码,方法AddUser将被拦截,并且不会被执行,而是现实执行拦截器方法,以下是输出:

 

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。




欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/) Powered by Discuz! X3.4