假设我有一个名为MyExtensionMethod的扩展方法。
我想这样使用它:
var x = new MyClass()
x.MyExtensionMethod()
然后,在扩展方法内部,我想获取调用它的引用的名称:
public static void MyExtensionMethod(this object param)
{
//get the name "x" somehow
}
这可能吗?
在C#中,这是不可能的。确保可用的信息如下:
如果您只是想简化参数检查,请在以下文件夹中创建一个文件:
%USERPROFILE%\ Documents \ Visual Studio 2012 \代码段\ Visual C#\我的代码段
如果您有多个版本的Visual Studio或与2012年不同的版本,则其他版本将存在一个适当命名的替代文件夹。
使用以下内容将文件命名为ThrowIfArgumentNull.snippet。要使用它,请tan
在编辑器中键入并按两次Tab键。您将获得IntelliSense的支持,用于输入参数名称,并且字符串参数将自动填写。该代码段创建了一个standard ArgumentNullException
,但是如果您的项目使用的是,您可以将其修改为使用Guard
或Argument
类。
<?xml version="1.0" encoding="utf-8"?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<CodeSnippet Format="1.0.0">
<Header>
<SnippetTypes>
<SnippetType>Expansion</SnippetType>
</SnippetTypes>
<Title>Throw if argument null</Title>
<Author>Sam Harwell</Author>
<Description>Throw an ArgumentNullException if the specified argument is null.</Description>
<HelpUrl>
</HelpUrl>
<Shortcut>tan</Shortcut>
</Header>
<Snippet>
<Declarations>
<Literal Editable="true">
<ID>arg</ID>
<ToolTip>arg</ToolTip>
<Default>arg</Default>
<Function>
</Function>
</Literal>
<Literal Editable="false">
<ID>ArgumentNullException</ID>
<ToolTip>ArgumentNullException</ToolTip>
<Default>ArgumentNullException</Default>
<Function>SimpleTypeName(global::System.ArgumentNullException)</Function>
</Literal>
</Declarations>
<Code Language="csharp"><![CDATA[if ($arg$ == null)
throw new $ArgumentNullException$("$arg$");$end$]]></Code>
</Snippet>
</CodeSnippet>
</CodeSnippets>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句