开发者

Create function to loop through properties of a method in C#?

What I am trying to do is create a function that will be called from each method within a .cs file to then get all of the pro开发者_开发技巧perty names and values that are passed to the method and create a string of them.

This will be used for a debug log to show what the value of each property was when the error occurred as an alternative to manually creating the string each time an error occurs.

Is this possible? I have looked at reflection and I think it is what I need but I am not sure about passing the current method from itself into the new function, and then inside of the function pulling the properties of the method out (I assume this is where the reflection comes into play.)


A simpler approach might be to catch the exception, and then only log the values of the properties you're interested in. Trying to achieve what you want to do using reflection is possibly over-engineering.

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


How about something like:

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

edit - Sorry I seem to have misread the question. I have no idea how to do what your asking, or even if it's possible.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜