Finding the variable name passed to a function

前端 未结 17 2152
广开言路
广开言路 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:44

    Do this

    var myVariable = 123;
    myVariable.Named(() => myVariable);
    var name = myVariable.Name();
    // use name how you like
    

    or naming in code by hand

    var myVariable = 123.Named("my variable");
    var name = myVariable.Name();
    

    using this class

    public static class ObjectInstanceExtensions
    {
        private static Dictionary namedInstances = new Dictionary();
    
        public static void Named(this T instance, Expression> expressionContainingOnlyYourInstance)
        {
            var name = ((MemberExpression)expressionContainingOnlyYourInstance.Body).Member.Name;
            instance.Named(name);            
        }
    
        public static T Named(this T instance, string named)
        {
            if (namedInstances.ContainsKey(instance)) namedInstances[instance] = named;
            else namedInstances.Add(instance, named);
            return instance;
        }        
    
        public static string Name(this T instance)
        {
            if (namedInstances.ContainsKey(instance)) return namedInstances[instance];
            throw new NotImplementedException("object has not been named");
        }        
    }
    

    Code tested and most elegant I can come up with.

提交回复
热议问题