代码段:在Visual Studio中自动完成ArgumentNullException

时间:2013-09-19 21:48:20

标签: visual-studio visual-studio-2012 autocomplete intellisense

我经常编写一个c#代码,如下所示:

    void func(object myObject)
    {
        if (myObject == null)
        {
            throw new ArgumentNullException("myObject");
        }
        ...

如何在Visual Studio 2012中为该类型的代码编写自动完成功能,以便我不必一直输入此内容?

3 个答案:

答案 0 :(得分:7)

由于没有兴趣,我将通过发布我自己的解决方案来关闭这个问题。将以下文件放入C:\Program Files (x86)\Microsoft Visual Studio 11.0\VC#\Snippets\1033\Visual C#\ifn.snippet将会起到作用:

<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  <CodeSnippet Format="1.0.0">
    <Header>
        <Title>ifn</Title>
        <Shortcut>ifn</Shortcut>
        <Description>Code snippet for if (arg==null)</Description>
        <Author>sam green</Author>
        <SnippetTypes>
            <SnippetType>Expansion</SnippetType>
            <SnippetType>SurroundsWith</SnippetType>
        </SnippetTypes>
    </Header>
    <Snippet>
        <Declarations>
            <Literal>
                <ID>argument</ID>
                <Default>arg</Default>
                <ToolTip>Argument</ToolTip>
            </Literal>
        </Declarations>
        <Code Language="csharp"><![CDATA[if ($argument$ == null)
        {
                    throw new ArgumentException("$argument$");
        }$end$]]>
        </Code>
    </Snippet>
  </CodeSnippet>
</CodeSnippets>

答案 1 :(得分:1)

我使用自动生成和猜测我想要的参数的关键字“argnull”为此定义了一个ReSharper快捷方式。我认为,它与您的解决方案大致相同,但您不需要使用XML或放置文件。

以下是ReSharper VB.NET方法的示例:

if $VAR$ is nothing then
  throw new ArgumentNullException("$VAR$")
end if

答案 2 :(得分:0)

为改善@galet的答案,以下是我的:

  • 使用简洁的单行if() throw;语句。
  • 使用更精确的ArgumentNullException而不是ArgumentException
  • 使用nameof()避免使用魔术弦(因此可以与Refactor-Renames完美配合)。
  • 使用the (safer) is null operator
<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  <CodeSnippet Format="1.0.0">
    <Header>
        <Title>ifn</Title>
        <Shortcut>ifn</Shortcut>
        <Description>Code snippet for if (arg==null)</Description>
        <Author>https://stackoverflow.com/questions/18905475</Author>
        <SnippetTypes>
            <SnippetType>Expansion</SnippetType>
            <SnippetType>SurroundsWith</SnippetType>
        </SnippetTypes>
    </Header>
    <Snippet>
        <Declarations>
            <Literal>
                <ID>argument</ID>
                <Default>arg</Default>
                <ToolTip>Argument</ToolTip>
            </Literal>
        </Declarations>
        <Code Language="csharp"><![CDATA[if( $argument$ is null ) throw new ArgumentNullException( nameof($argument$) );$end$]]>
        </Code>
    </Snippet>
  </CodeSnippet>
</CodeSnippets>
相关问题