在Java中,可以使用AspectJ在执行方法之前和之后使用方法注释添加行为。由于C#属性似乎非常相似,所以我想知道是否有可能实现类似的行为。我一直在寻找的几个教程和其他来源(1,2,3),但没有人帮助我。
我认为也许可以通过将代码插入Attribute构造函数并使其成为可处理的方式来模仿行为,如下所示:
[AttributeUsage(AttributeTargets.Method)]
public class MyWritingAttribute : Attribute, IDisposable
{
public MyWritingAttribute()
{
Console.WriteLine("Attribute created");
}
public void Dispose()
{
Console.WriteLine("Attribute disposed");
}
}
Run Code Online (Sandbox Code Playgroud)
但是,当使用这样的属性时,只有Hello world!在控制台中显示:
class Program
{
static void Main(string[] args)
{
SayHelloWorld();
Console.ReadLine();
}
[MyWriting]
private static void SayHelloWorld()
{
Console.WriteLine("Hello World!");
}
}
Run Code Online (Sandbox Code Playgroud)
我当时在想控制台可能无法在该属性中访问,但是即使将其替换为throw new Exception()表达式,也不会引发异常。StringLengthAttributeEF 如何运作,但我的属性甚至没有实例化?以及如何使属性在修饰方法之前和之后运行?