Is it possible to write code like this?
public void DoSomeOperation().Log()
{
}.Log()
Above call will execute Log() function while entering the DoSomeOperation method and while exiting the method. Can i do something like that? I know i can use AOP here but without using AOP, does .NET give this kind of luxary?
Am I missing something, or wouldn't it just look like this?
public void DoSomeOperation()
{
Log();
// Rest of method body
Log();
}
If you mean to add the Log()
calls to an existing DoSomeOperation()
method, you could perhaps just override it like this if it's virtual:
public override void DoSomeOperation()
{
Log();
base.DoSomeOperation();
Log();
}
Or better yet use a wrapper method and pass in a delegate of the respective method as LukeH suggests .
As to actually decorating every method invocation in your class with Log()
calls, I don't believe C# offers such a feature. Not as far as I know, anyway.
LogWrapper(DoSomeOperation);
LogWrapper(() => DoSomeOtherOperation(42));
LogWrapper(() => AndAnother("example"));
// ...
public static void LogWrapper(Action action)
{
Log();
action();
Log();
}
No, that is not possible. You'd have to write it like so:
public void DoSomeOperation()
{
Log();
// ....
Log();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.