How can I Invoke a method in a class whenever a method in the same class is called?
Instead of doing this:
public class MyClass
{
private void InvokeMe() { }
public void Method1()
{
this.InvokeMe();
// some codes
}
public void Method2()
{
this.InvokeMe();
// some codes
}
public void Method3()
{
this.InvokeMe();
// some codes
}
// more methods
}
I want to automatically invoke the InvokeMe private method instead of putting it on each of the public methods in MyClass because we have too many method in that class and that class always change.
My code is in C#, Framework 4.0, build in Visual Studio 2010 Pro.
Please help, Thanks in advance.
This could be accomplished using some Aspect programming (take a look at PostSharp or one of its alternatives). Alternatively since you are using .NET 4 you could create a DynamicObject implementation to act as a proxy for your class and when a method is called on it have it call the
InvokeMemethod first.UPDATE
I’ve added a link to the
DynamicObjectdocumentation above for further reading. There’s a good MSDN blog available here that discusses the relevant points.