代码之家  ›  专栏  ›  技术社区  ›  David

将属性重构为字段

  •  3
  • David  · 技术社区  · 14 年前

    如果我有一个字段,则可以通过右键单击字段->重构->封装字段来生成相应的属性。

    我有这样的财产

    public int Foo { get; set; }
    

    我想生成私有字段并将getter和setter更改为使用该字段。然后,我可以实现INotifyPropertyChanged,并在属性值更改时将setter更改为激发PropertyChanged事件。

    private int _foo;
    public int Foo
    {
        get { return _foo;}
        set 
        {
            if (value != _foo)
            {
                _foo = value;
                NotifyPropertyChanged("Foo");
            }
        }
    }
    
    3 回复  |  直到 12 年前
        1
  •  2
  •   Dr. Wily's Apprentice    14 年前

    2个选项:

    1. 创建代码段。这不会自动为您重构任何现有属性,但至少可以允许您快速重新创建属性(如果您想手动创建)。 例如,在“My Documents\Visual Studio 2008\Code Snippets\Visual C\My Code Snippets”文件夹中创建包含以下内容的“propv.snippet”文件。然后,您可以通过在intellisense弹出窗口中选择“propv”来创建带有“backing”字段的属性:

      <?xml version="1.0" encoding="utf-8" ?>
      <CodeSnippets  xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
          <CodeSnippet Format="1.0.0">
              <Header>
                  <Title>propv</Title>
                  <Shortcut>propv</Shortcut>
                  <Description>Code snippet for property and backing field</Description>
                  <Author>Dr. Wily's Apprentice</Author>
                  <SnippetTypes>
                      <SnippetType>Expansion</SnippetType>
                  </SnippetTypes>
              </Header>
              <Snippet>
                  <Declarations>
                      <Literal>
                          <ID>type</ID>
                          <ToolTip>Property type</ToolTip>
                          <Default>int</Default>
                      </Literal>
                      <Literal>
                          <ID>property</ID>
                          <ToolTip>Property name</ToolTip>
                          <Default>MyProperty</Default>
                      </Literal>
                      <Literal>
                          <ID>field</ID>
                          <ToolTip>The variable backing this property</ToolTip>
                          <Default>myVar</Default>
                      </Literal>
                  </Declarations>
                  <Code Language="csharp">
                      <![CDATA[private $type$ $field$;
      
      
      public $type$ $property$
      {
      get { return $field$;}
      set { $field$ = value;}
      }$end$]]>
                  </Code>
              </Snippet>
          </CodeSnippet>
      </CodeSnippets>
      
    2. 使用Visual Studio中的宏录制功能或其他工具(Notepad++)录制重构属性所需的步骤,然后在需要时运行该宏。

        2
  •  1
  •   Reed Copsey    14 年前

    不幸的是 Resharper 也不是 Refactor Pro 也包括这个作为标准功能。实现INPC有太多的选择。

    ),点击tab键并键入属性的名称-其他所有内容,包括backing字段,都是从中自动生成的。

        3
  •  1
  •   Piers Myers    14 年前

    Resharper 因为它可以为您添加更多的重构选项。他们的实时模板比Visual Studio的片段更易于使用。