gpt4 book ai didi

c# - 在构造函数中抛出 ArgumentNullException?

转载 作者:IT王子 更新时间:2023-10-29 03:50:04 24 4
gpt4 key购买 nike

对于具有单个参数的构造函数,如果参数为 null/空,是否可以在构造函数内部抛出 ArgumentNullException?或者,它应该在实际使用参数的方法中抛出吗?谢谢。

最佳答案

是的,如果它是完全必要的,那么抛出异常。你以后不应该*抛出异常。

永远记住"Fail Early Principle" .概念现在失败了,所以您不会浪费时间调试或遇到意外的系统功能。

或者,您也可以为“”抛出 ArgumentException,为 null 抛出 ArgumentNullException。无论哪种情况,请确保抛出有效的异常消息。


始终是管理异常的好引用文章:Good Exception Management Rules of Thumb


@Steve Michelotti 所说的旁注(因为我是 CodeContracts 的 super 粉丝)

Contract.Requires<ArgumentNullException>(inputParemeter!= null, "inputparameter cannot be null");
Contract.Requires<ArgumentException>(inputParemeter!= "", "inputparameter cannot be empty string");

或者

Contract.Requires<ArgumentNullException>(!string.IsNullOrEmpty(inputParemeter), "inputparameter cannot be null or empty string");

关于c# - 在构造函数中抛出 ArgumentNullException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3629849/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com