当前位置:网站首页>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
边栏推荐
- Uniapp image import local image not displayed
- Mui close other pages and keep only the first page
- 100 GIS practical application cases (53) - making three-dimensional image map as the base map of urban spatial pattern analysis
- 「玩转Lighthouse」轻量应用服务器自建DNS解析服务器
- SQL exercise question 1
- Embrace the new blue ocean of machine vision and hope to open a new "Ji" encounter for the development of digital economy
- 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.
- (1) Openjuterpyrab comparison scheme
- Jupiter notebook installation
- Conflict between Mui picker and drop-down refresh
猜你喜欢
Free and open source intelligent charging pile SaaS cloud platform of Internet of things
Remote access to raspberry pie at home (Part 1)
The project file '' has been renamed or is no longer in the solution, and the source control provider associated with the solution could not be found - two engineering problems
Complete project data of UAV apriltag dynamic tracking landing based on openmv (LabVIEW + openmv + apriltag + punctual atom four axes)
Read the data in Presto through sparksql and save it to Clickhouse
nodejs + mysql 实现简单注册功能(小demo)
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?
[untitled] PID control TT encoder motor
22. 括号生成
初鉴canvas,展示个小小的小案例
随机推荐
产品开发都应该知道的8个网站,增强工作体验
MySQL —— 16、索引的数据结构
将新增和编辑的数据同步更新到列表
Van uploader upload picture implementation process, using native input to upload pictures
Wu Enda's programming assignment - logistic regression with a neural network mindset
[51 single chip microcomputer traffic light simulation]
Utils of various date conversion
Mysql8 installation
31. 下一个排列
教你快速开发一个 狼人杀微信小程序(附源码)
Softbank vision fund entered the Web3 security industry and led a new round of investment of US $60 million in certik
STM32 is connected to the motor drive, the DuPont line supplies power, and then the back burning problem
Read the data in Presto through sparksql and save it to Clickhouse
31. Next arrangement
Melt reshape decast long data short data length conversion data cleaning row column conversion
8 websites that should be known for product development to enhance work experience
Learning notes of AMBA protocol
Customize the shortcut options in El date picker, and dynamically set the disabled date
这几种 VSCode 扩展是我最喜欢的
melt reshape decast 长数据短数据 长短转化 数据清洗 行列转化