Appearance
[Fit] 标注
[Fit]标注用于面向切面编程和动态代理,用于标注切面对象和动态代理对象适合的用于哪些类型;或者用在切面的方法上,用于标注适用于哪些方法
Fit的语法说明
Fit采用正常的逻辑运算。同时有以下方法可以使用
| 方法名 | 说明 | 示例 | 适用范围 |
|---|---|---|---|
| class() | 匹配抽象类 | class() | Type |
| interface() | 匹配接口 | interface() | Type |
| name() | 匹配名称(含命名空间),参数是正则表达式 | name('AsDI\\.*') | Type,Method |
| attr() | 匹配标注名称(含命名空间),参数是正则表达式 | attr('AsDI\\.Fit*') | Type,Method |
| super() | 匹配父类或继承接口的名称(含命名空间),参数是正则表达式 | super('AsDI\\.Fit*') | Type |
Fit的用途
[Fit]用于标注切面或动态代理,说明这个切面或动态代理的适用范围。如下列示例
示例1 - 适用所有类型
C#
[Fit("1")]
public class LogInterceptor : IInterceptor表示当前LogInterceptor适用于所有类型
示例2 - 适用所有抽象类
C#
[Fit("class()")]
public class LogInterceptor : IInterceptor表示当前LogInterceptor适用于所有抽象类
示例3 - 适用所有接口
C#
[Fit("interface()")]
public class LogInterceptor : IInterceptor表示当前LogInterceptor适用于所有接口
示例4 - 适用于某个名称
C#
[Fit(@"name('AsDI\\.Example\\.*')")]
public class LogInterceptor : IInterceptor表示当前LogInterceptor适用于以 AsDI.Example. 开头的所有类型和接口
需要说明的是,name对应的是类型的全名称,即 命名空间.类名
示例5 - 适用于含有某个标注
C#
[Fit(@"attr('AsDI\\.Example\\.LogAttribute')")]
public class LogInterceptor : IInterceptor表示当前LogInterceptor适用于含有 AsDI.Example.LogAttribute 标注的所有类型和接口
示例6 - 适用于继承自某个类型或接口
C#
[Fit(@"super('System\\.IDisposable')")]
public class LogInterceptor : IInterceptor表示当前LogInterceptor适用继承自 System.IDisposable 的所有类型和接口
示例7 - 综合示例
C#
[Fit(@" interface()
&& attr('AsDI\\.Example\\.LogAttribute')
&& !super('System\\.IDisposable')")]
public class LogInterceptor : IInterceptor表示当前LogInterceptor适用含有 AsDI.Example.LogAttribute 标注且 不 继承自 System.IDisposable 的接口
应用于方法
应用于方法,主要用于在切面的Around方法上进行标注
C#
[Fit("1")]
public class LogInterceptor : IInterceptor
{
[Fit("name('^Get.*')")]
public object Around(AspectEntity aspect)
{
...
}
}表示当前LogInterceptor只适用于名称以 "Get" 开头的方法
自定义Fit
可以通过继承FitAttribute类型,然后override Fit 方法,定义自己的Fit方式,例如
C#
public sealed class CustomFitAttribute : FitAttribute
{
public override bool Fit(Type type)
{
if (type.Name.Contains("Service"))
{
return true;
}
return false;
}
}
[CustomFit]
public class LogInterceptor : IInterceptor
...如果是应用于方法的Fit,需要 override 适用于方法的Fit方法,例如:
C#
public sealed class CustomFitAttribute : FitAttribute
{
public override bool Fit(MethodInfo method)
{
if (method.GetCustomAttribute<LogAttribute>() == null)
{
return false;
}
return true;
}
}