Finding the variable name passed to a function

前端 未结 17 2178
广开言路
广开言路 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 05:00

    GateKiller, what's wrong with my workaround? You could rewrite your function trivially to use it (I've taken the liberty to improve the function on the fly):

    static string sMessages(Expression>> aMessages) {
        var messages = aMessages.Compile()();
    
        if (messages.Count == 0) {
            return "";
        }
    
        StringBuilder ret = new StringBuilder();
        string sType = ((MemberExpression)aMessages.Body).Member.Name;
    
        ret.AppendFormat("

    ", sType); foreach (string msg in messages) { ret.Append(msg); ret.Append("
    "); } ret.Append("

    "); return ret.ToString(); }

    Call it like this:

    var errors = new List() { "Hi", "foo" };
    var ret = sMessages(() => errors);
    

提交回复
热议问题