namespace MyExtensions
{
public static class MyExtensions
{
[System.Runtime.CompilerServices.Extension()]
public static bool LogError<T>(this T exp, string errorType = "",string extramessage = "") where T : System.Exception
{
if (!exp.Message.ToString().ToLower().Contains("thread was being aborted"))
{
string strDate = DateTime.Now.Date.ToString("yyyy-MM");
string FilePath = (HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["Errors"]) + "LogError-" + strDate + ".txt");
FileInfo myFile = new FileInfo(FilePath);
StreamWriter sWriter = new StreamWriter(FilePath, true);
sWriter.WriteLine(("#------------" + DateTime.Now.ToString("dd-MM-yyyy hh:mm:ss tt") + "------------#"));
sWriter.WriteLine(("Source: " + exp.Source));
sWriter.WriteLine(("Method: " + exp.TargetSite.Name));
sWriter.WriteLine(("Message: " + exp.Message));
if (exp.InnerException != null)
{
sWriter.WriteLine(("Inner Exception: " + exp.InnerException.Message));
}
sWriter.WriteLine(("StackTrace: " + exp.StackTrace));
if (!string.IsNullOrEmpty(extramessage))
{
sWriter.WriteLine(" -- Extra Message: -- ");
sWriter.WriteLine(extramessage);
}
sWriter.WriteLine("#------------------------------------------------#");
sWriter.WriteLine();
sWriter.WriteLine();
sWriter.Close();
}
return true;
}
}
}
我有這樣的類,它包含一個擴展方法稱爲LogError
我創建了一個ASP的形式,然後是服務器端的代碼如下所示:擴展是不是在我的.cs類中找到
using MyExtensions
public partial class Form : BasePage
{
public void GetEmpleye()
{
try{}
catch(Exception ex)
{ ex.LogError(); }
}
}
ex.LogError();
這線是給我一個錯誤說:
System.Extension不包含
定義LogError
你'MyExtensions'類被打破入手 - 這是一個靜態類,但是你已經把在構造函數中。這是不允許的,所以你應該在那裏得到一個錯誤。接下來,你的'LogError'方法是一個實例方法,最後它沒有'this'作爲第一個參數的修飾符。 –
擴展方法必須是靜態的,第一個參數應該是「this T exp」。 – Silvermind
請檢查我的編輯 – Sora