简体   繁体   中英

Resharper convert auto-property to full property

I found the opposite here , but I need to frequently change from auto-property to full property - would it be possible to automate that (and with a shortcut perhaps):

From Auto-Property

public string FirstName { get; set; }

To Property with Backing Field

    private string _firstName;

    public string FirstName
    {
        get
        {
            return _firstName;
        }
        set
        {
            _firstName = value;
        }
    }

Obviously, I would then change the full property further...

Place your cursor on the property name, then wait a second or two. Press the Resharper hotkey sequence (Alt-Enter) and the second option should be "To property with backing field" which is what you want.

Alternatively, you can click the "hammer" icon in the left margin to get the option.

To make it work (ALT-Enter) you must to configure resharper keyboard schema. VS -> Tools -> Options -> ReSharper -> General -> Options -> Keyboard and menus -> Resharper keyboard Schema -> Visual Studio

I would like to add an extended solution which also allows to create a property in this style, that has support for INotifyPropertyChanged for viewmodels:

public string Name
{
    get => _name;
    set
    {
        if (value == _name) return;
        _name = value;
        RaisePropertyChanged();
    }
}

/// <summary>
/// Raises the <see cref="PropertyChanged"/> event for the given <paramref name="propertyName"/>.
///
/// The <see cref="NotifyPropertyChangedInvocatorAttribute"/> attribute is used
/// because of Resharper support for "to property with change notification":
/// https://www.jetbrains.com/help/resharper/Coding_Assistance__INotifyPropertyChanged_Support.html
/// </summary>
/// <param name="propertyName"></param>
[NotifyPropertyChangedInvocator]
public virtual void RaisePropertyChanged([CallerMemberName] string propertyName = null)
{
    PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}

The required steps are:

  • Install the Nuget package "JetBrains.Annotations" in the project were your viewmodels are located
  • Use the [NotifyPropertyChangedInvocator] attribute on the method where the PropertyChanged event is raised
  • After that, the option "To property with change notification" is available for the properties of your viewmodels

在此处输入图像描述


See also: Jetbrains INotifyPropertyChanged support

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