如果我有一个字段,我可以通过右键单击字段生成相应的属性 - >重构 - >封装场。
有没有办法让事情相反?
我有像
这样的属性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");
}
}
}
答案 0 :(得分:2)
2个选项:
创建代码段。这不会自动为您重构任何现有属性,但至少它可以让您快速重新创建属性,如果您想手动完成。 例如,在“My Documents \ Visual Studio 2008 \ Code Snippets \ Visual C#\ My Code Snippets”文件夹中创建一个“propv.snippet”文件,其中包含以下内容。然后,您可以通过在intellisense弹出窗口中选择“propv”来创建具有支持字段的属性:
<?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>
使用Visual Studio中的宏录制功能或其他工具(Notepad ++)记录重构属性所需的步骤,然后在需要时运行该宏。
答案 1 :(得分:1)
Visual Studio内部没有包含重构。
不幸的是,Resharper和Refactor Pro都不包含此标准功能。实施INPC的选择太多了。
话虽这么说,我确实有一个Resharper模板,它生成一个实现INPC的属性。使用此方法,您可以键入一个小关键字(我的是 propno ),点击标签,然后输入属性的名称 - 其他所有内容(包括支持字段)都是从该位置自动生成的。
答案 2 :(得分:1)
看看Resharper因为它可以为你做这个以及更多的重构选项。他们的实时模板比Visual Studio的片段更容易使用。