How to get current property name via reflection?

后端 未结 8 730
悲哀的现实
悲哀的现实 2020-12-02 16:54

I would like to get property name when I\'m in it via reflection mechanism. Is it possible?

Update: I have code like this:

    public CarType Car
            


        
8条回答
  •  自闭症患者
    2020-12-02 17:39

    Way # 1

    var a = nameof(SampleMethod);    //a == SampleMethod
    var b = nameof(SampleVariable);  //b == SampleVariable
    var c = nameof(SampleProperty);  //c == SampleProperty
    

    Way # 2

    MethodBase.GetCurrentMethod().Name; // Name of method in which you call the code
    MethodBase.GetCurrentMethod().Name.Replace("set_", "").Replace("get_", ""); // current Property
    

    Way # 3

    from StackTrace:

    public static class Props
    {
        public static string CurrPropName => 
             (new StackTrace()).GetFrame(1).GetMethod().Name.Replace("set_", "").Replace("get_", "");
    
        public static string CurrMethodName => 
            (new StackTrace()).GetFrame(1).GetMethod().Name;
    }
    

    you just need to call Props.CurrPropName or Props.CurrMethodName


    Way # 4

    Solution for .NET 4.5+:

    public static class Props
    {
        public static string GetCallerName([System.Runtime.CompilerServices.CallerMemberName] String propertyName = "")
        {
             return propertyName;
        }
    }
    

    usgae: Props.GetCallerName();

提交回复
热议问题