开发者

Getting method parameters as an object[] in C#

开发者 https://www.devze.com 2023-03-25 04:22 出处:网络
Is there any dark, obscured way to convert all of the method parameters to an object[]? While implementing the integration between two systems using a message broker, I noticed that most of the metho

Is there any dark, obscured way to convert all of the method parameters to an object[]?

While implementing the integration between two systems using a message broker, I noticed that most of the methods exposed by the broker uses a lot of parameters.

I want an easy way to l开发者_如何学Pythonog each call to the broker with every parameter. Something like:

[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
}

I'm curious if C# provides something that simulates GetMethodArgs();


You could just have 2 methods.

[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 can capture this using a method boundary aspect. Here's some sample code to see it in action.

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);
        }
    }
}

The output is:

abc
234


For logging/auditing purposes, I have used Castle.DynamicProxy to wrap the Web Service implementation. All method calls are intercepted and passed to an IInterceptor object that has access to the parameters and the return value.

0

精彩评论

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

关注公众号