如何访问继承的值

Jos*_*mez 1 c# inheritance

我有一个方法,异常变量作为参数.此异常有时可以从自定义异常继承其他值,除了它的默认值之外,我想知道如何在不转换为自定义异常对象或验证的情况下访问这些自定义值HResult(由于方法的参数如何,这将始终相同) ).

例如,在某些情况下,异常对象可以继承列表,但我无法访问此列表.要使此方法返回正确的值,我必须首先找到识别异常的方法,并且通过访问继承的值,我将能够.

这是我到目前为止所尝试的:

- 异常处理方法 -

private string ExceptionHandler(Exception ex)
{
    var customExceptionMessages = string.Empty;

    //I want to avoid this
    var customException = ex as CustomException;

    if (customException != null)
    {
        //Build custom exception message
        foreach (var v in customException.CustomViolations)
        {
            customExceptionMessages += v.ErrorMessage + "<br />";
        }

        return customExceptionMessages;
    }

    else
        return ex.Message;
}
Run Code Online (Sandbox Code Playgroud)

- 使用示例 -

ExceptionHandler(customEx);
Run Code Online (Sandbox Code Playgroud)

调试之后,我注意到在ExceptionHandler运行之前,customEx 它有用户定义的值.之后ExceptionHandler开始运行,ex继承异常,加上自定义的默认值.我不能只说ex.CustomViolations因为这只存在于运行时.

Rob*_* S. 5

覆盖Message自定义异常类中的属性,并在属性getter中构建所需的消息字符串.完成后,您可以简单地返回ex.Message,而不必担心异常类型.

public class CustomException : Exception
{
     public override string Message
     {
         get
         {
             return <build message here>;
         }
     }
}
Run Code Online (Sandbox Code Playgroud)