[英]How to get method name automatically in Code Snippet in C# 4.0
我正在使用C#在ASP.Net 4.0中开发一个应用程序,我正在使用Microsoft的Enterprise Lib进行日志记录和跟踪。 我的问题是几乎在每个函数中,根据我公司的guidline,与数据库或一些关键业务规则的交互,使用这种格式的跟踪。
try
{
_traceLog.clear();
_traceLog.AppendLine("XYZ method started: XYZ()");
_traceLog.AppendLine("XYZ method completed: XYZ()");
}
catch(Exception ex)
{
_userException.CreateExceptionLog(ex);
}
finally
{
_userException.CreateTraceLog(_traceLog.ToString());
}
所以我想要的是将它转换为自动检测当前方法的代码片段,比如上面我们有XYZ()的情况。
请帮我。 还告诉我将其添加到intellisense的方法。 现在我可以创建.snippet文件并使用上下文菜单中的插入片段。
更新
我想我不清楚你们。 让我说清楚一点。 我有一个代码片段
<CodeSnippets
xmlns="http://schemas.microsoft.com/VisualStudio/2010/CodeSnippet">
<CodeSnippet Format="1.0.0">
<Header>
<Title>
TL
</Title>
</Header>
<Snippet>
<Code Language="CSharp">
<![CDATA[ try
{
_traceLog.Clear();
_traceLog.AppendLine(""); // here in side the append line i want to get name of method under which i am placing code snippet.
_traceLog.AppendLine("");
}
catch (Exception ex)
{
_userExceptionLog.CreateExceptionLog(ex);
}
finally
{
_userExceptionLog.CreateTraceLog(_traceLog.ToString());
}]]>
</Code>
</Snippet>
</CodeSnippet>
</CodeSnippets>
例如,如果我的方法是
void XYZ()
{
// when i insert snippet here , the snippet will automatically detect
该片段将被置于XYZ函数下。
try
{
_traceLog.Clear();
_traceLog.AppendLine("XYZ started: XYZ()");
//在旁边的附加行我想得到方法的名称,我在其中放置代码片段。
_traceLog.AppendLine("XYZ completed: XYZ()");
}
catch (Exception ex)
{
_userExceptionLog.CreateExceptionLog(ex);
}
finally
{
_userExceptionLog.CreateTraceLog(_traceLog.ToString());
}
}
这可能吗? 或者我必须手动输入或以其他任何方式输入?
MethodInfo.GetCurrentMethod().Name
将为您提供当前正在执行的方法的名称。 警告:匿名方法会给你垃圾的名字。
我用这个:
try
{
}
catch ( Exception ex )
{
My.API.ErrorHandler.Handler.HandleError( ex,
System.Reflection.MethodBase.GetCurrentMethod().Name,
System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName );
}
以下是代码段的代码:
<?xml version="1.0" encoding="utf-8"?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<CodeSnippet Format="1.0.0">
<Header>
<Title>Try Catch</Title>
<Shortcut>try</Shortcut>
<Description>Places a try catch block with My API error handling</Description>
<Author>Nathan Freeman-Smith</Author>
</Header>
<Snippet>
<Code Language="csharp"><![CDATA[ try
{
}
catch ( Exception ex )
{
My.API.ErrorHandler.Handler.HandleError( ex, System.Reflection.MethodBase.GetCurrentMethod().Name, System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName );
}]]></Code>
</Snippet>
</CodeSnippet>
</CodeSnippets>
注意Shortcut标签里面有“try”。
这意味着我可以通过在visual studio中输入try来插入片段来使用该片段,或者,使用Ctrl + k,Ctrl + S(Deafult Keyboard Shourtcut)标记一段代码并用此snippt包围它
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.