2011-01-19 61 views
0

1)我創建了一個測試例外。C#用戶定義的異常,在異常之間轉換?

public class TestException : Exception 
{ 
    string info; 
    public string Info { get { return info; } set { info = value; } } 
    public TestException() { } 
    public TestException(string message) : base(message) { } 
    public TestException(string message, Exception inner) : base(message, inner) { } 
    protected TestException(
     System.Runtime.Serialization.SerializationInfo info, 
     System.Runtime.Serialization.StreamingContext context) 
     : base(info, context) { } 
} 

2)在函數中的某處網站我有這樣的事情:

catch (Exception e) 
{ 
    TestException myOwnException = new TestException(e); 
    myOwnException.Info = "test"; 
    LogError(myOwnException); 
} 

但是我不能從基本異常投上我的課。 logError需要一個TestException。

我想我的異常類中創建這個(可以讓我寫TestException myOwnException = E;)

public static implicit operator TestException(Exception e) 
{ 
    return new TestException(e); 
} 

但我只是不斷收到: 用戶定義的轉換或從基類不允許。

如何將catch語句的異常轉換爲我的TestException類? (我也試過TestException test =(TestException)e;但是這只是返回一個錯誤

+0

什麼是LogError – sukru 2011-01-19 19:45:30

回答

3

我會保持這個簡短的,你不能使這個工作,你需要改變LogError()方法爲接受一個異常對象。如果需要任何附加的狀態(如信息)然後添加作爲參數傳遞給LOGERROR()方法,或者使過載。

0

但是我不能從基座 例外投logError 需要一個TestException。

你的文章中的代碼是es不涉及從Exception到TestException的強制轉換。 LogError中是否存在轉換?如果你不確定,你能否發佈LogError的內容?在不嘗試添加隱式轉換運算符的情況下看到問題的確切細節也會有所幫助。