How to get current property name via reflection?

后端 未结 8 768
悲哀的现实
悲哀的现实 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

    Use MethodBase.GetCurrentMethod() instead!

    Reflection is used to do work with types that can't be done at compile time. Getting the name of the property accessor you're in can be decided at compile time so you probably shouldn't use reflection for it.

    You get use the accessor method's name from the call stack using System.Diagnostics.StackTrace though.

        string GetPropertyName()
        {
            StackTrace callStackTrace = new StackTrace();
            StackFrame propertyFrame = callStackTrace.GetFrame(1); // 1: below GetPropertyName frame
            string properyAccessorName = propertyFrame.GetMethod().Name;
    
            return properyAccessorName.Replace("get_","").Replace("set_","");
        }
    

提交回复
热议问题