print name of the variable in c#

前端 未结 5 1353
小鲜肉
小鲜肉 2020-12-08 17:27

i have a statement

int A = 10,B=6,C=5;

and i want to write a print function such that i pass the int variable to it and it prints me the va

5条回答
  •  情歌与酒
    2020-12-08 17:51

    Another solution (from a closed post):

    Inspired by Jon Skeet's post about Null Reference exception handling and suddenly being reminded about projection there is a way to kinda do that.

    Here is complete working codez:

    public static class ObjectExtensions {
        public static string GetVariableName(this T obj) {
            System.Reflection.PropertyInfo[] objGetTypeGetProperties = obj.GetType().GetProperties();
    
            if(objGetTypeGetProperties.Length == 1)
                return objGetTypeGetProperties[0].Name;
            else
                throw new ArgumentException("object must contain one property");
        }
    }
    
    class Program {
        static void Main(string[] args) {
            string strName = "sdsd";
            Console.WriteLine(new {strName}.GetVariableName());
    
            int intName = 2343;
            Console.WriteLine(new { intName }.GetVariableName());
        }
    }
    

提交回复
热议问题