[英]can i have an Extention method for a method?
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. 上面的调用将在进入DoSomeOperation方法和退出该方法时执行Log()函数。 Can i do something like that? 我可以那样做吗? I know i can use AOP here but without using AOP, does .NET give this kind of luxary? 我知道我可以在这里使用AOP,但不使用AOP,.NET是否可以提供这种奢华?
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: 如果您打算将Log()
调用添加到现有的DoSomeOperation()
方法,则可以在虚拟的情况下像这样重写它:
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 . 或者更好的方法是使用包装方法,并按照LukeH的建议传入相应方法的委托。
As to actually decorating every method invocation in your class with Log()
calls, I don't believe C# offers such a feature. 至于实际上使用Log()
调用装饰类中的每个方法调用,我都不认为C#提供了这样的功能。 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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.