gpt4 book ai didi

c# - 一种通用的集中式参数记录器方法,在 C# 中

转载 作者:太空狗 更新时间:2023-10-30 00:26:59 25 4
gpt4 key购买 nike

考虑这个 JavaScript 代码片段:

Object.prototype.log = function() {
// here, you have a centralized place to do logging stuff;
console.log(this);
}

function fullName(firstName, lastName)
{
// here, using a simple one-line code, you can log all parameters;
arguments.log();
}

fullName('saeed', 'nemati');

我们能否在 C# 中使用类似的机制来记录传递给方法的所有参数?

注意:我所做的是使用反射,但没有成功:

public static void LogParameters(this ParameterInfo[] parameters)
{
StringBuilder builder = new StringBuilder();
builder.Append("*****************\r\n");
builder.Append("Parameters\r\n");
parameters.ToList().ForEach(pi =>
{
builder.AppendFormat("{0} => {1}\r\n", pi.Name, pi.DefaultValue);
// The problem is that, I can't get the value of the parameter here
});
builder.Append("*****************");
Log.Write(builder.ToString());
}

public string GetFullName(string firstName, string lastName)
{
MethodBase.GetCurrentMethod().GetParameters().LogParameters();
return firstName + " - " + lastName;
}

GetFullName("saeed", "neamati");

最佳答案

不,您不能使用反射获取参数值。您必须将它们显式传递到日志记录方法中。

您可以使用调试器 API 来完成此操作,但您可能不想这样做。如果我是你,我会明确地这样做 - 事实上,这可能最终会产生更有用的日志记录,因为你可以只记录重要的内容,并在消息中提供一些上下文。

关于c# - 一种通用的集中式参数记录器方法,在 C# 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8665505/

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