[英]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.