攔截器Interceptors是一種可以在編譯時以聲明方式替換原有應用的方法。
這種替換是通過讓Interceptors聲明它攔截的調用的源位置來實現(xiàn)的。
您可以使用攔截器作為源生成器的一部分進行修改,而不是向現(xiàn)有源編譯添加代碼。
?文章來源地址http://www.zghlxwxcb.cn/news/detail-841684.html
演示
使用 .NET 8 創(chuàng)建一個控制臺應用程序。并在PropertyGroup中添加以下配置.。需要將其中WebApplication6替換為自己的命名空間。
<InterceptorsPreviewNamespaces>$(InterceptorsPreviewNamespaces);WebApplication6</InterceptorsPreviewNamespaces>
然后在單獨的文件中創(chuàng)建InterceptsLocationAttribute。其命名空間必須是System.Runtime.CompilerServices,而不是應用程序的命名空間。
namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] public sealed class InterceptsLocationAttribute(string filePath, int line, int character) : Attribute { } }
該屬性包含三個參數(shù)。
- filePath是您要攔截的文件的路徑。
- line是您要攔截的代碼行。
- character是您要攔截的代碼字符位置。
接著來創(chuàng)建一個具有三種方法的類,模擬新增/查詢用戶作為示例:
public class GetUserService { // This method will not be intercepted; public void GetUserName() { Console.WriteLine("GetUserName"); } // This method will be intercepted; public void AddUser() { Console.WriteLine("AddUser"); } // This method will not be intercepted; public void DeleteUser() { Console.WriteLine("DeleteUser"); } }
在 Program.cs 文件中,我創(chuàng)建了此類的一個實例,并創(chuàng)建了對這三個方法中每一個的調用。輸出如下所示:
var userService = new GetUserService(); userService.GetUserName(); userService.AddUser(); userService.DeleteUser();
現(xiàn)在讓我們創(chuàng)建攔截類。該類必須遵循以下規(guī)則:
- 一定是一個static類。
- 必須是我們要攔截的類的擴展方法。
- 必須具有該InterceptsLocation屬性,其中包含我們要攔截的文件路徑的值以及行號和字符號。
?
using System.Runtime.CompilerServices; namespace WebApplication6 { public static class InterceptUserService { [InterceptsLocation( filePath: @"D:\demo\test\ConsoleApp1\WebApplication6\Program.cs", line: 14, character: 25)] public static void InterceptMethodAddUser(this GetUserService example) { Console.WriteLine("Interceptor is here!"); } } }
在此示例中,將攔截AddUser方法,并且將執(zhí)行InterceptMethodAddUser方法,而不是執(zhí)行方法AddUser。
filePath可以按以下方式獲取
?
行號和字符號可以按以下方式獲取
?
現(xiàn)在運行代碼,方法AddUser將被攔截,并且不會被執(zhí)行,而是實際執(zhí)行攔截器方法,以下是輸出:
文章來源:http://www.zghlxwxcb.cn/news/detail-841684.html
?
到了這里,關于C# 12 攔截器 Interceptors的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網!