Is there any way to write a custom class which extends .NET Attribute class so that I can apply that class on a method and .NET Framew开发者_运维知识库ork calls my class constructor before executing that method. Here is the example
public class TestAttribute : Attribute
{
public TestAttribute()
{
Console.WriteLine("Called");
}
}
class Program
{
static void Main(string[] args)
{
TestMethod();
}
[TestAttribute()]
public static void TestMethod()
{
}
}
I want when TestMethod is called, framework will execute TestAttribute() constructor.
In regular .NET attributes don't cause magic invocation, except for a very limited set of system attributes (security etc). The rest are applied only by inspection through reflection, which has to be done explicitly.
You might look at PostSharp (now renamed into a commercial product).
I don't believe so - Attributes are only read by things reflecting over the code, they aren't called during normal execution.
Yes it is possible, but not as is.
You can do that by using Aspect Oriented Programming. PostSharp is a framework that allows you to do that; it allows you to 'weave' aspects into the code at compile time.
Postsharp
[Serializable]
public class TestAttribute : OnMethodInvocationAspect
{
public override void OnInvocation()
{
Console.WriteLine ("TestAttribute called");
base.OnInvocation();
}
}
精彩评论