How do I get the name of a property from a property in C# (2.0)

后端 未结 7 673
春和景丽
春和景丽 2020-12-10 17:24

I know I could have an attribute but that\'s more work than I want to go to... and not general enough.

I want to do something like

class Whotsit
{
          


        
相关标签:
7条回答
  • 2020-12-10 17:59

    It is possible (without reflection) but only with latest C# 3.0

    quick & very very dirty

    class Program
    {
        static void Main()
        {
            string propertyName = GetName(() => AppDomain.CurrentDomain);
            Console.WriteLine(propertyName); // prints "CurrentDomain"
            Console.ReadLine();
        }
    
        public static string GetName(Expression<Func<object>> property)
        {
            return property.Body.ToString().Split('.').Last();
        }
    }
    

    Update: I've just realized that Jon Skeet (anyone surprised? :) has covered this possibility already but I'll keep my answer here just in case someone is interested in some example to start with.

    0 讨论(0)
提交回复
热议问题