Visual Studio 2017带有.this的propfull代码片段

4
你好,我经常在VS中使用propfull片段,但每次都需要添加".this",因为快捷方式不包括它。你知道在哪里可以找到能实现这一点的代码片段吗(适用于没有resharper的VS 2017)?我搜索过了,但最好的结果是一个resharper版本,但对我来说这不起作用。如果此问题已经发布在其他地方,请原谅我没有找到答案。

示例:

普通propfull:

    private int myVar;

    public int MyProperty
    {
        get { return myVar; }
        set { myVar = value; }
    }

期望的属性:

    private int myVar;

    public int MyProperty
    {
        get { return this.myVar; }
        set { this.myVar = value; }
    }

说实话,如果你只是返回后备字段,不要创建自己的后备字段,因为 VS 会为你创建。在 C# 6 中,你甚至可以将它们用作只读后备字段,这样你就可以从构造函数内部设置它们(所以你只需要定义 public int MyProperty { get; })。 - Icepickle
你为什么要这个呢? - Crowcoder
是的,我同意你的看法。但是大多数时候,我必须在Setter中进行某种验证,因此我更喜欢使用this.someName以获得更清晰的方法。 :) - Stoyan Grigorov
你知道resharper会将“this”标记为多余吗? - Icepickle
目前我没有使用 ReSharper,但如果我错了,请纠正我。对我来说,使用它有点像个人偏好。 - Stoyan Grigorov
@StoyanGrigorov 当然,我只是指出这并不是大多数人的偏好。 - Icepickle
1个回答

4
您可以通过在 Visual Studio 中找到的“工具”菜单下的代码片段管理器来实现此操作...

enter image description here

我以微软代码片段中的propfull实现为例,并稍作修改,使其在属性前添加此内容,如下所示:
<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets  xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  <CodeSnippet Format="1.0.0">
    <Header>
      <Title>propfull with this</Title>
      <Shortcut>thispropfull</Shortcut>
      <Description>Code snippet for property and backing field</Description>
      <Author>Icepickle</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 this.$field$;}
    set { this.$field$ = value;}
  }
  $end$]]>
      </Code>
    </Snippet>
  </CodeSnippet>
</CodeSnippets>

您可以将此文件另存为自己的代码片段(扩展名为.snippet),然后使用导入按钮添加您自己的代码片段。然后,您可以编写快捷方式thispropfull,它将创建所需的代码片段。

enter image description here


非常感谢,这就是我想要的! :) 你太棒了 :) - Stoyan Grigorov
很高兴能帮助到你 :) - Icepickle

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接