C# User defined exception, cast between exceptions?
1) I have created a test exception.
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 inf开发者_Python百科o,
System.Runtime.Serialization.StreamingContext context)
: base(info, context) { }
}
2) In a function somewhere in the website i got something like this:
catch (Exception e)
{
TestException myOwnException = new TestException(e);
myOwnException.Info = "test";
LogError(myOwnException);
}
However i can't cast from the base exception to my class. The logError expects a TestException.
I tried creating this inside my Exception class (Would allow me to write TestException myOwnException = e;)
public static implicit operator TestException(Exception e)
{
return new TestException(e);
}
But i just keep getting: user-defined conversions to or from a base class are not allowed.
How can i cast the exception from the catch statement into my TestException class? (I have also tried TestException test = (TestException)e; but that just returns an error.
I'll keep this short, you just cannot make this work. You'll need to change the LogError() method to accept an Exception object. If any additional state is required (like Info) then add that as an argument to the LogError() method. Or make an overload.
However i can't cast from the base exception to my class. The logError expects a TestException.
The code in your post does not involve a cast from Exception to TestException. Is there a cast in LogError? If you're not sure, could you please post the contents of LogError? The exact details of the problem you see without attempting to add the implicit cast operator would also be helpful.
精彩评论