2010-08-23 21 views
3

我想要做的是创建一个函数,将从.cs文件中的每个方法调用,然后获取传递给该方法的所有属性名称和值并创建它们的字符串。创建函数来循环通过C#中的方法的属性?

这将用于调试日志,以显示错误发生时每个属性的值是什么,作为每次发生错误时手动创建字符串的替代方法。

这可能吗?我看过反射,我认为这是我需要的,但我不确定将当前方法从自身传递到新函数,然后在函数内部拉动方法的属性(我假设这是)

+0

可能的重复:http://stackoverflow.com/questions/1820630/how-to-get-parameter-value-from-stacktrace – 2010-08-23 15:38:03

回答

1

更简单的方法可能是捕获异常,然后只记录您感兴趣的属性的值。尝试使用反射来实现您想要执行的操作可能是过度工程。

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; 
} 
+0

这个问题是我有超过100多种方法来改变日志记录。所以我将不得不手动编辑它们中的每一个,这是我尝试创建一个函数来完成这一切的唯一原因。 – Miva 2010-08-23 15:48:31

+0

那么我想这对你来说不是一个好的解决方案。不过,在编写新代码尝试使用这种模式时需要考虑一些事情 - 它现在已经为您节省了麻烦! – 2010-08-23 15:57:47

+0

这就是我最终做的 - PITA,但它的工作。 – Miva 2010-10-29 12:51:21

1

看看这个链接dumping objects - 它也解释了你需要管理的嵌套级别/你想要深入对象堆栈的深度。

2

如何像:

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

编辑 - 对不起,我似乎误解了问题。我不知道如何去做你的要求,甚至是否有可能。

+0

如何: http://stackoverflow.com/questions/2405230/can-i-get-parameter-names-values-procedurally-from-the-currently-executing-functi – asawyer 2010-08-23 17:48:13