当前位置:网站首页>Introduction to metalama 4 Use fabric to manipulate items or namespaces
Introduction to metalama 4 Use fabric to manipulate items or namespaces
2022-04-23 13:06:00 【severe provisions】
Metalama Medium Fabric What can be done
Fabric By modifying the project 、 Namespace 、 Type to achieve some results , This led to changes including : add to Aspect Or add code analysis
Use Fabric Add... For the specified method Aspect
In the previous article, we wrote a simple Aspect:
public class LogAttribute : OverrideMethodAspect
{
public override dynamic? OverrideMethod()
{
Console.WriteLine(meta.Target.Method.ToDisplayString() + " Began to run .");
var result = meta.Proceed();
Console.WriteLine(meta.Target.Method.ToDisplayString() + " End operation .");
return result;
}
}
When we use it , We need to add this to the corresponding method Attribute:
[Log]
private static int Add(int a, int b) //... ...
So when we have a Aspect When you want to use it extensively in a project , Add this... To each method Aspect Of course it's a way , But this method has 2 Disadvantages :
- Contains a lot of duplicate code
[Log] - The intrusion of the original code is too strong
Now we can use Fabric Add the specified... For all methods that meet the requirements Aspect:
internal class Fabric : ProjectFabric
{
// This is to rewrite the project Fabric How to modify the project in
public override void AmendProject(IProjectAmender amender)
{
// add to LogAttribute To the method that conforms to the rules
// It's called Add And private To add LogAttribute
amender.WithTargetMembers(c =>
c.Types.SelectMany(t => t.Methods)
.Where(t =>
t.Name == "Add" &&
t.Accessibility == Metalama.Framework.Code.Accessibility.Private)
).AddAspect(t => new LogAttribute());
}
}
This allows you to add... To the specified method without invading existing code Aspect.
Use Fabric Add code analysis
We mentioned above , We can go through Aspect Add code analysis to your code , When we want to include ( And only ) Code analysis Aspect When applied to a batch of code , Of course, we can follow this article Example 1 The method in , Use it directly Fabric Will include code analysis Aspect Apply to specified code .
But there is another way , We can go straight to Fabric Defines the code analysis that applies to the specified code .
The following example , We verify that private fields in all classes must conform to _camelCase, And use a NamespaceFabric To achieve :
namespace FabricCamelCaseDemo;
class Fabric : NamespaceFabric
{
private static readonly DiagnosticDefinition<string> _warning = new(
"DEMO04",
Severity.Warning,
"'{0}' Hump nomenclature must be used and marked with '_' start ");
// This is a namespace Fabric Modify namespace rules in Methods
public override void AmendNamespace(INamespaceAmender amender)
{
// Take all non static Of private Field of , And add code analysis
amender.WithTargetMembers(c =>
c.AllTypes.SelectMany(t=>t.Fields)
.Where(t => t.Accessibility == Accessibility.Private && !t.IsStatic
)
)
//preview 0.5.8 For before RegisterFinalValidator
.Validate(this.FinalValidator);
}
private void FinalValidator(in DeclarationValidationContext context)
{
var fullname = context.Declaration.ToDisplayString();
var fieldName = fullname.Split('.').LastOrDefault();
if (fieldName!=null && (!fieldName.StartsWith("_") || !char.IsLower(fieldName[1])))
{
context.Diagnostics.Report(_warning.WithArguments(fieldName));
}
}
}
Of course, because the current use is NamespaceFabric Therefore, this rule only applies to the current namespace, such as , If we define a rule violating field in another namespace , There will be no warning .
namespace FabricCamelCase;
internal class OtherNamespace
{
int count = 0;
int _total = 0;
public int Add()
{
count++;
_total++;
return count + _total;
}
}
Use TypeFabric Dynamically add methods to types
Forge a requirement before you start , Suppose I have a class AddUtils Specialized in addition operations , There should be something in it from 2 A to 15 Parameters Add Method 15 individual ( Of course I know , have access to params And so on , So this is a pseudo requirement ).
The final effect is
public class AddUtils
{
public int Add2(int x1, int x2)
{
var result = 0;
result += x1;
result += x2;
return 2;
}
public int Add3(int x1, int x2, int x3)
{
var result = 0;
result += x1;
result += x2;
result += x3;
return 3;
}
// And so on ... Several methods are omitted below
}
Then we can use Metalama This is how it works
using System.Reflection.Emit;
using Metalama.Framework.Aspects;
using Metalama.Framework.Fabrics;
public class AddUtils
{
private class Fabric : TypeFabric
{
// The method body of implementation
[Template]
public int MethodTemplate()
{
var num = (int) meta.Tags["nums"]!;
var result = 0;
foreach (var targetParameter in meta.Target.Parameters)
{
result += targetParameter.Value;
}
return num;
}
public override void AmendType(ITypeAmender amender)
{
for (var i = 2; i < 15; i++)
{
// Generate a method
var methodBuilder = amender.Advices.IntroduceMethod(
amender.Type,
nameof(this.MethodTemplate),
tags: new TagDictionary { ["nums"] = i });
// Method name
methodBuilder.Name = "Add" + i;
// Add parameter
for (int parameterIndex = 1; parameterIndex <= i; parameterIndex++)
{
methodBuilder.AddParameter($"x{parameterIndex}", typeof(int));
}
}
}
}
}
quote
Source code of this chapter :https://github.com/chsword/metalama-demo
Metalama Official documents : https://doc.metalama.net/
Metalama Nuget package : https://www.nuget.org/packages/Metalama.Framework/0.5.11-preview
版权声明
本文为[severe provisions]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204231300586909.html
边栏推荐
- mysql8安装
- 5 free audio material websites, recommended collection
- Van uploader upload picture implementation process, using native input to upload pictures
- Proteus 8.10 installation problem (personal test is stable and does not flash back!)
- Navicat远程连接数据库 出现 1130- Host xxx is not allowed to connect to this MySQL server错误
- Record the problems encountered in using v-print
- 7_Addmodule和基因加和法add 得到的细胞类型打分在空间上空转对比
- Teach you to quickly develop a werewolf killing wechat applet (with source code)
- There is no need to crack the markdown editing tool typora
- AUTOSAR from introduction to mastery 100 lectures (52) - diagnosis and communication management function unit
猜你喜欢

Softbank vision fund entered the Web3 security industry and led a new round of investment of US $60 million in certik

Learning notes of AMBA protocol

World Book Day: I'd like to recommend these books

进程虚拟地址空间区域划分

filter()遍历Array异常友好

100 lectures on practical application cases of Excel (VIII) - report connection function of Excel

Navicat远程连接数据库 出现 1130- Host xxx is not allowed to connect to this MySQL server错误

8086 of x86 architecture

100 GIS practical application cases (52) - how to keep the number of rows and columns consistent and aligned when cutting grids with grids in ArcGIS?

Kernel error: no rule to make target 'Debian / canonical certs pem‘, needed by ‘certs/x509_ certificate_ list‘
随机推荐
AUTOSAR from introduction to mastery 100 lectures (52) - diagnosis and communication management function unit
基于uniapp异步封装接口请求简介
100 GIS practical application cases (34) - splicing 2020globeland30
ECDSA signature verification principle and C language implementation
「玩转Lighthouse」轻量应用服务器自建DNS解析服务器
Learning materials
31. 下一个排列
将新增和编辑的数据同步更新到列表
HQL find the maximum value in a range
100 GIS practical application cases (52) - how to keep the number of rows and columns consistent and aligned when cutting grids with grids in ArcGIS?
7_ The cell type scores obtained by addmodule and gene addition method are compared in space
AUTOSAR from introduction to mastery 100 lectures (50) - AUTOSAR memory management series - ECU abstraction layer and MCAL layer
SQL exercise question 1
Wonderful review | the sixth issue of "source" - open source economy and industrial investment
Design of body fat detection system based on 51 single chip microcomputer (51 + OLED + hx711 + US100)
AUTOSAR from introduction to mastery 100 lectures (83) - bootloader self refresh
The accuracy and speed are perfectly balanced, and the latest image segmentation SOTA model is released!!!
AUTOSAR from introduction to mastery lecture 100 (84) - Summary of UDS time parameters
Free and open source agricultural Internet of things cloud platform (version: 3.0.1)
[untitled] make a 0-99 counter, P1 7 connected to key, P2 connected to nixie tube section, common anode nixie tube, P3 0,P3. 1. Connect the nixie tube bit code. Each time you press the key, the nixie