[英]Get the name of parameters from a calling method
I have a project using C# .NET 2.0 (cannot use a higher version). 我有一个使用C#.NET 2.0的项目(不能使用更高版本)。 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.
如果我从MyMethodsClass调用方法,则要遵循MyCheckClass类的isValid方法中指示的某些条件,接收一个指示哪个参数无效的字符串。
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). 使用以下代码,如果我将调用myMehtod(5,1,1),我将得到一个返回“请检查5参数”的字符串。 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();
}
}
You combine two things you already know how to do. 您将已经知道如何做的两件事结合在一起。
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.