开发者

Is it possible to retrieve the argument name from an argument value in C#?

I'd like to know whether I can retrieve an argument name from an argument value. I need this functionality because I've build myself a static class (called Requires) to make argument checking in meth开发者_如何学Pythonod bodies a one-liner. Currently, the validation methods are implemented like this:

Requires.StringNotNullOrEmpty(string argName, string argValue) {...}

To validate an argument, you have to provide the name of the argument (later used to throw a meaningful ArgumentException) and its value.

My question is, is there a way to retrieve the argument name from an argument value inside a method body?

Thanks in advance and happy easter!


I think you are looking for Reflection.

Reflection: How to Invoke Method with parameters


class A
{
    public void MyMethod(int num, string aString)
    { 
        ParameterInfo[] parameters = typeof(A).GetMethod("MyMethod", BindingFlags.Public|BindingFlags.Instance).GetParameters();
        string secondParameterName = parameters[1].Name;   //you will get aString
    }
}


No, you cannot know the name used by the calling code - because in many cases, what's been passed to your method doesn't have a name at all, e.g. it could be an expression, or a literal. So there's no general solution to this.


No. Point. You know the name of the arbument (argName). You can not know what is was SET from because... that is not even part of the argument. It is part of the knowledge of the outer class, not the argument (which would return argName).


Not sure if this is what you had in mind

internal class TestClass
{

private void DoSomething(string myArg)
{
    // returns the name of the argument = "myArg"
    string myArgName = GetArgumentName(() => myArg);
    // check
    System.Diagnostics.Debug.Assert(string.Compare("myArg", myArgName, System.StringComparison.InvariantCulture) == 0, "names do not match");
}


private static string GetArgumentName<T>(System.Linq.Expressions.Expression<System.Func<T>> argument)
{
    string argumentName = null;
    System.Linq.Expressions.MemberExpression body = (System.Linq.Expressions.MemberExpression)argument.Body;
    if (body.Member != null)
    {
        argumentName = body.Member.Name;
    }

    if (argumentName == null)
    {
        // could not retrieve argument name
    }

    return argumentName;
}

}

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜