开发者

Use AOP in C# to detect if return value is used

开发者 https://www.devze.com 2022-12-11 02:54 出处:网络
This is related to my other question, but this time very开发者_如何学JAVA specific. Is it possible, using AOP (PostSharp in particular) to detect if function\'s return value was used? For example

This is related to my other question, but this time very开发者_如何学JAVA specific. Is it possible, using AOP (PostSharp in particular) to detect if function's return value was used? For example

var x = y.func();  // used
y.func(); // not used

Note that detection should be performed for this particular call, not for the function in general.

I never used AOP/PostSharp so even if I don't find answer in PostSharp's docs I can't be sure it's not there. I do not insist on PostSharp, though; I'm OK to use any library as long as it can do the job.


You can't use AOP for that, but it's quite easy (when you know the tool) to write some MSIL analysis that does the job.

Basically, when a method return value is not used, there is a 'pop' instruction just after the 'call' or 'callvirt'. You could do PostSharp to do the job (use the low-level weaver, define an IAdvice intercepting calls of the method you want, define an InstructionSequence bookmark, read one more instruction, test if it is 'pop', and rollback to the bookmark so that the scan can continue safely.

But I wonder why you would need that and I agree with Nicole's answer.


While it's very likely possible, it's very much the wrong tool for the job, so you would end up doing more work than necessary to implement a solution. I would recommend that you return to your other question and focus on finding a better candidate approach instead of focusing on how you might sink a nail with a screwdriver...

0

精彩评论

暂无评论...
验证码 换一张
取 消