当前位置:网站首页>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
边栏推荐
- There is no need to crack the markdown editing tool typora
- Timing role in the project
- Mui close other pages and keep only the first page
- Teach you to quickly develop a werewolf killing wechat applet (with source code)
- MySQL —— 16、索引的数据结构
- 100 lectures on practical application cases of Excel (VIII) - report connection function of Excel
- Golang implements MD5, sha256 and bcrypt encryption
- Free and open source agricultural Internet of things cloud platform (version: 3.0.1)
- CVPR 2022&NTIRE 2022|首个用于高光谱图像重建的 Transformer
- Packet capturing and sorting -- TCP protocol [8]
猜你喜欢
MySQL —— 16、索引的数据结构
Design of STM32 multi-channel temperature measurement wireless transmission alarm system (industrial timing temperature measurement / engine room temperature timing detection, etc.)
Design and manufacture of 51 single chip microcomputer solar charging treasure with low voltage alarm (complete code data)
有趣的IDEA插件推荐,给你的开发工作增添色彩
Software testing weekly (issue 68): the best way to solve difficult problems is to wait and see the changes and push the boat with the current.
Install nngraph
Use Proteus to simulate STM32 ultrasonic srf04 ranging! Code+Proteus
World Book Day: I'd like to recommend these books
Importerror after tensorflow installation: DLL load failed: the specified module cannot be found, and the domestic installation is slow
22. Bracket generation
随机推荐
Go language mapping operation
mui picker和下拉刷新冲突问题
Software testing weekly (issue 68): the best way to solve difficult problems is to wait and see the changes and push the boat with the current.
产品开发都应该知道的8个网站,增强工作体验
How to convert opencv pictures to bytes
Important knowledge of transport layer (interview, retest, final)
Kernel error: no rule to make target 'Debian / canonical certs pem‘, needed by ‘certs/x509_ certificate_ list‘
JMeter operation redis
4.22 study record (you only did water problems in one day, didn't you)
CMSIS cm3 source code annotation
1130 - host XXX is not allowed to connect to this MySQL server error in Navicat remote connection database
Translation of attention in natural language processing
【微信小程序】flex布局使用记录
4.22学习记录(你一天只做了水题是吗)
Conflict between Mui picker and drop-down refresh
51 single chip microcomputer stepping motor control system based on LabVIEW upper computer (upper computer code + lower computer source code + ad schematic + 51 complete development environment)
Use of Presto date function
Customize the shortcut options in El date picker, and dynamically set the disabled date
Pytorch: a pit about the implementation of gradreverselayer
Huawei cloud MVP email