Create a function to scroll through method properties in C #?

What I'm trying to do is create a function that will be called from each method in the .cs file, to then get all the names and values ​​of the properties that are passed to the method and create their string.

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

Is it possible? I looked at the reflections and I think that this is what I need, but I'm not sure about passing the current method from myself to a new function, and then inside the function that pulls out the properties of the method (I assume this reflection plays.)

+3
source share
3 answers

A simpler approach might be to catch an exception and then only register property values ​​that interest you. Trying to achieve what you want to do using reflection is perhaps too complex.

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;
}
+1
source

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 misunderstood the question. I do not know how to do what you ask, or even if it is possible.

+2
source

- , /, .

+1

Source: https://habr.com/ru/post/1761138/


All Articles