Visual Studio: Is it possible to define custom functions for use in one's own Code Snippets?

一笑奈何 提交于 2019-12-10 12:46:26

问题


I want to write a Visual Studio snippet which allows me to quickly create a class of the form:

public SomeClass
{
    public SomeType SomeProperty { get; private set; }
    public SomeClass(SomeType someProperty) { SomeProperty = someProperty; }
}

I want the parameter on the constructor to have the same name as the property, but lower-cased. I don't want to have to type the name twice. How do I do this?

I've already looked at the XML for snippets and I discovered that there are certain functions that can be used. For example, the built-in "switch" code snippet contains the following instruction:

<Function>GenerateSwitchCases($expression$)</Function>

According to this MSDN documentation page, there are three built-in functions that you can use in this <Function> tag. Unfortunately, neither of them does what I want (lower-case the first letter). Is it possible to define a function that I can then use in my snippet?


回答1:


No this is not possible in Visual Studio today. The definition and execution of snippet functions is directly controlled by the C# language service. It is not currently an extensibility point. It is being considered for a future version of the product though.




回答2:


Check out this article on creating a code snippet that defines variables that can be used several times and have to be typed only once: http://www.switchonthecode.com/tutorials/csharp-tutorial-visual-studio-code-snippets

<Snippet>
  <Declarations>
    <Literal>
      <ID>startTime</ID>
      <ToolTip>Beginning Time Variable</ToolTip>
      <Default>startTime</Default>
    </Literal>
    <Literal>
      <ID>message</ID>
      <ToolTip>Replace This With Your Description</ToolTip>
      <Default>My function</Default>
    </Literal>
    <Literal Editable="false">
      <ID>DiagnosticsDebug</ID>
      <Function>
        SimpleTypeName(global::System.Diagnostics.Debug)
      </Function>
    </Literal>
  </Declarations>
  <Code Language="CSharp">
    <![CDATA[
   long $startTime$ = Environment.TickCount;
   $selected$ $end$
   $DiagnosticsDebug$.WriteLine(String.Format(
       "$message$ took {0} ticks.", Environment.TickCount - $startTime$));
   ]]>
  </Code>
</Snippet>


来源:https://stackoverflow.com/questions/2266415/visual-studio-is-it-possible-to-define-custom-functions-for-use-in-ones-own-co

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!