简体   繁体   中英

C# 6: nameof() current property in getter/setter

Is there a way to get the name of the current property in a getter/setter?

Something like this:

public string MyProperty
{
    get { return base.Get<string>(nameof(ThisProperty)); }
    set { base.Set<string>(nameof(ThisProperty), value); }
}

nameof(ThisProperty) should resolve to "MyProperty".

It can't be done with nameof , but there's an even better way (available since C# 5). You can make the propertyName parameter optional and apply the CallerMemberName attribute to it:

protected void Set<T>(T value, [CallerMemberName] string propertyName = null)
{
    ...
}

protected T Get<T>([CallerMemberName] string propertyName = null)
{
    ...
}

Now if you omit the argument for propertyName , the current member name is passed implicitly:

public string MyProperty
{
    get { return base.Get<string>(); } // same as calling Get<string>("MyProperty")
    set { base.Set<string>(value); } // same as calling Set<string>(value, "MyProperty")
}

Alternative is to the the MethodBase since a Get and Set are essentially methods.

public string MyProperty
{
    get
    {
        return MethodBase.GetCurrentMethod().Name.Substring(4);
    }            
}

The substring is there because each name is prefixed with get_ and set_

This returns MyProperty as the result.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM