Finding the variable name passed to a function

前端 未结 17 2226
广开言路
广开言路 2020-11-22 04:11

Let me use the following example to explain my question:

public string ExampleFunction(string Variable) {
    return something;
}

string WhatIsMyName = "         


        
17条回答
  •  我寻月下人不归
    2020-11-22 04:40

    What you want isn't possible directly but you can use Expressions in C# 3.0:

    public void ExampleFunction(Expression> f) {
        Console.WriteLine((f.Body as MemberExpression).Member.Name);
    }
    
    ExampleFunction(x => WhatIsMyName);
    

    Note that this relies on unspecified behaviour and while it does work in Microsoft’s current C# and VB compilers, and in Mono’s C# compiler, there’s no guarantee that this won’t stop working in future versions.

提交回复
热议问题