在C#中将方法参数作为对象获取
是否有任何黑暗,模糊的方法将所有方法参数转换为对象[]?
在使用消息代理实现两个系统之间的集成时,我注意到代理公开的大多数方法都使用了大量参数。
我想要一个简单的方法来记录每个参数的每个调用代理。 就像是:
[WebMethod] public void CreateAccount(string arg1, int arg2, DateTime arg3, ... ) { object[] args = GetMethodArgs(); string log = args.Aggregate("", (current, next) => string.Format("{0}{1};", current, next)); Logger.Log("Creating new Account: " + args); // create account logic }
我很好奇C#是否提供了模拟GetMethodArgs()的东西;
你可以有两种方法。
[WebMethod] public void CreateAccount(string arg1, int arg2, DateTime arg3) { CreateAccountImpl(arg1, arg2, arg3); } protected void CreateAccountImpl(params object[] args) { string log = args.Aggregate("", (current, next) => string.Format("{0}{1};", current, next)); Logger.Log("Creating new Account: " + args); // create account logic }
PostSharp可以使用方法边界方面捕获它。 这是一些示例代码,可以看到它的实际效果。
public sealed class Program { public static void Main() { Go("abc", 234); } [ParamAspect] static void Go(string a, int b) { } } [Serializable] public class ParamAspect : OnMethodBoundaryAspect { public override void OnEntry(MethodExecutionArgs args) { object[] argumentContents = args.Arguments.ToArray(); foreach (var ar in argumentContents) { Console.WriteLine(ar); } } }
输出是:
abc 234
出于日志记录/审计的目的,我使用Castle.DynamicProxy来包装Web Service实现。 拦截所有方法调用并将其传递给可以访问参数和返回值的IInterceptor对象。
上述就是C#学习教程:在C#中将方法参数作为对象获取分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/943562.html