gpt4 book ai didi

postsharp - 获取参数名称

转载 作者:行者123 更新时间:2023-12-05 01:02:31 27 4
gpt4 key购买 nike

你如何得到参数姓名 的一种方法。这些示例向您展示了如何获取 参数,但不是 姓名 .我想看到 parma = 99, parmb = 1。不仅仅是 99, 1。

    using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using PostSharp.Aspects;

namespace GettingParmNames
{
public class Program
{
static void Main(string[] args)
{
Foo myfoo = new Foo();
int sum = myfoo.DoA(99, 1);
Console.WriteLine(sum.ToString());

Console.ReadKey();
}
}

public class Foo
{
[ExceptionAspect]
public int DoA(int parma, int parmb)
{
int retVal;
try
{
retVal = parma + parmb;
if (parma == 99)
{
throw new Exception("Fake Exception");
}

}
catch (Exception ex)
{
retVal = -1;
throw new Exception("There was a problem");
}

return retVal;
}
}

[Serializable]
public class ExceptionAspect : OnExceptionAspect
{
public override void OnException(MethodExecutionArgs args)
{
string parameterValues = "";

foreach (object arg in args.Arguments)
{
if (parameterValues.Length > 0)
{
parameterValues += ", ";
}

if (arg != null)
{
parameterValues += arg.ToString();
}
else
{
parameterValues += "null";
}
}

Console.WriteLine("Exception {0} in {1}.{2} invoked with arguments {3}", args.Exception.GetType().Name, args.Method.DeclaringType.FullName, args.Method.Name, parameterValues );
}
}

}

最佳答案

您可以在 OnException 中访问方法参数的信息。方法通过调用 args.Method.GetParameters() .但出于性能原因,通常最好在编译时初始化数据 - 在 CompileTimeInitialize 中方法覆盖。

[Serializable]
public class ExceptionAspect : OnExceptionAspect
{
private string[] parameterNames;

public override void CompileTimeInitialize(MethodBase method, AspectInfo aspectInfo)
{
parameterNames = method.GetParameters().Select(p => p.Name).ToArray();
}

public override void OnException(MethodExecutionArgs args)
{
StringBuilder parameterValues = new StringBuilder();

for (int i = 0; i < args.Arguments.Count; i++)
{
if ( parameterValues.Length > 0 )
{
parameterValues.Append(", ");
}

parameterValues.AppendFormat(
"{0} = {1}", parameterNames[i], args.Arguments[i] ?? "null");
}

// ...
}

关于postsharp - 获取参数名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26219226/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com