简体   繁体   中英

Get the name of parameters from a calling method

I have a project using C# .NET 2.0 (cannot use a higher version). I would like to get the name of the parameters of a method in a method called by the first one. If I call a method from the MyMethodsClass, I want to receive a string indicating which parameter is not valid, following some conditions indicated in the isValid method from the MyCheckClass class.

With the following code, I get a string that returns "Please check the 5 parameter" in case I would call the myMehtod(5,1,1). But I would like to obtain, "Please check the a parameter".

How could I do that? Thank you!

public MyMethodsClass {

    public string myMethod (int a, int b, int c) {

        return MyCheckClass.isValid(a,b,c);
    }

    public string myMethod2 (int d, int e) {
        return MyCheckClass.isValid(d,e);
    }

}


//Other file
public class MyCheckClass {

    public static string isValid (params object[] parameters) {

            StringBuilder result= new StringBuilder();          
            for (int i = 0; i < parameters.Length; i++)
            {
                object p = parameters[i];
                //Some checks...
                if (p == null || p.Equals("") || p != 5)
                {                    
                    result.Append("Please check the " + p + " parameter");
                }
            }
            return result.toString();               
    }
}

These two line should do the job for you, perhaps need to adapt but should work ^^

        MethodInfo info = typeof (MyMethodsClass).GetMethod("MethodName");
        string name = info.GetParameters()[indexOfTheFaultyOne].Name;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM