我想要做的是创建一个函数,将从.cs文件中的每个方法调用,然后获取传递给该方法的所有属性名称和值并创建它们的字符串。创建函数来循环通过C#中的方法的属性?
这将用于调试日志,以显示错误发生时每个属性的值是什么,作为每次发生错误时手动创建字符串的替代方法。
这可能吗?我看过反射,我认为这是我需要的,但我不确定将当前方法从自身传递到新函数,然后在函数内部拉动方法的属性(我假设这是)
我想要做的是创建一个函数,将从.cs文件中的每个方法调用,然后获取传递给该方法的所有属性名称和值并创建它们的字符串。创建函数来循环通过C#中的方法的属性?
这将用于调试日志,以显示错误发生时每个属性的值是什么,作为每次发生错误时手动创建字符串的替代方法。
这可能吗?我看过反射,我认为这是我需要的,但我不确定将当前方法从自身传递到新函数,然后在函数内部拉动方法的属性(我假设这是)
更简单的方法可能是捕获异常,然后只记录您感兴趣的属性的值。尝试使用反射来实现您想要执行的操作可能是过度工程。
ABC abc = new ABC();
try {
a.xyz = "Runtime value";
//Exception thrown here ...
}
catch (Exception ex)
{
Log.LogDebugFormatted(
"Exception caught. abc.xyz value: {0}. Exception: {1}", abc.xyz, ex);
throw ex;
}
看看这个链接dumping objects - 它也解释了你需要管理的嵌套级别/你想要深入对象堆栈的深度。
如何像:
void Main()
{
var test = new TestObject();
test.a = "123";
test.b = "456";
var testProperties = (from prop in test.GetType().GetProperties()
select new KeyValuePair<string,string>(prop.Name,prop.GetValue(test,null).ToString()));
foreach (var property in testProperties)
{
Console.WriteLine(string.Format("Name: {1}{0}Value: {2}",Environment.NewLine,property.Key,property.Value));
}
var testMethods = (from meth in test.GetType().GetMethods() select new { Name = meth.Name, Parameters =
(from param in meth.GetParameters()
select new {Name = param.Name, ParamType=param.GetType().Name})});
foreach (var method in testMethods)
{
Console.WriteLine(string.Format("Method: {0}",method.Name));
foreach(var param in method.Parameters)
{
Console.WriteLine("Param: " + param.Name + " (" + param.ParamType + ")");
}
}
}
class TestObject
{
public string a { get; set; }
public string b { get; set; }
public string testMethod(string param1,int param2){return string.Empty;}
}
编辑 - 对不起,我似乎误解了问题。我不知道如何去做你的要求,甚至是否有可能。
如何: http://stackoverflow.com/questions/2405230/can-i-get-parameter-names-values-procedurally-from-the-currently-executing-functi – asawyer 2010-08-23 17:48:13
可能的重复:http://stackoverflow.com/questions/1820630/how-to-get-parameter-value-from-stacktrace – 2010-08-23 15:38:03