繁体   English   中英

使用自定义异常 class

[英]Using a custom exception class

我创建了这个自定义异常 class。 我希望能够将错误分配给更多错误。 当我实例化 SampleException 并将错误分配给 moreErrors 时,它始终是 null

我在这里做错了什么?

        public class SampleException : Exception
        {
            public SampleException(string message):base(message)
            {
            }

            public IEnumerable<string> moreErrors { get; set; }
        }

你可以像下面这样使用它:

public class SampleException : Exception
{
    public SampleException(string message, List<string> errorList = null) : base(message)
    {
        ErrorList = errorList;
    }

    public List<string> ErrorList { get; set; }
}

并抛出这样的异常:

throw new SampleException("Error Message", new List<string>() { "Error 1", "Error 2" });

'ErrorList' 属性是 null 因为它没有被初始化为任何东西。

虽然您无法将其初始化为 IEnumerable<string>(这是抽象的),但您可以将其初始化为 List<string>。 那你应该对go好。

    public class SampleException : Exception
    {
        public SampleException(string message) : base(message)
        {
        }

        public List<string> MoreErrors { get; set; } = new List<string>();
    }

暂无
暂无

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

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