How to get current property name via reflection?

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

    Slightly confusing example you presented, unless I just don't get it. From C# 6.0 you can use the nameof operator.

    public CarType MyProperty
    {
        get { return (CarType)this[nameof(MyProperty)]};
        set { this[nameof(MyProperty)] = value]};
    }
    

    If you have a method that handles your getter/setter anyway, you can use the C# 4.5 CallerMemberName attribute, in this case you don't even need to repeat the name.

    public CarType MyProperty
    {
        get { return Get(); }
        set { Set(value); }
    }
    
    public T Get([CallerMemberName]string name = null)
    {
        return (T)this[name];
    }   
    
    public void Set(T value, [CallerMemberName]string name = null)
    {
        this[name] = value;
    }  
    

提交回复
热议问题