繁体   English   中英

C#用户定义的异常,在异常之间转换?

[英]C# User defined exception, cast between exceptions?

1)我创建了一个测试异常。

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。

我尝试在我的Exception类中创建它(请允许我编写TestException myOwnException = e;)

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

但是我一直在获取:不允许用户定义的向基类或从基类的转换。

如何将catch语句中的异常强制转换为TestException类? (我也尝试过TestException test =(TestException)e;但这只会返回错误。

我会简短地说,您就是无法完成这项工作。 您需要更改LogError()方法以接受Exception对象。 如果需要任何其他状态(例如Info),则将其作为参数添加到LogError()方法。 或重载。

但是我不能从基本异常转换为我的课程。 logError需要TestException。

您帖子中的代码不涉及从Exception到TestException的转换。 LogError中是否有演员表? 如果不确定,可以将LogError的内容发布吗? 您在未尝试添加隐式强制转换运算符的情况下所看到的问题的确切详细信息也将有所帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM