当尝试将重复的对象插入集合时,什么是正确的.NET异常? [英] What is the correct .NET exception to throw when try to insert a duplicate object into a collection?

查看:105
本文介绍了当尝试将重复的对象插入集合时,什么是正确的.NET异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Asset对象,它有一个属性AssignedSoftware,它是一个集合。

I have an Asset object that has a property AssignedSoftware, which is a collection.

我想确保同一软件不会多次分配给资产。在添加方法中,我检查软件是否已经存在,如果存在,我想抛出异常。

I want to make sure that the same piece of Software is not assigned to an Asset more than once. In Add method I check to see if the Software already exist, and if it does, I want to throw an exception.

有没有标准的.NET异常,我应该抛出?

Is there a standard .NET exception that I should be throwing? Or does best practices dictate I create my own custom exception?

推荐答案

从类库设计指南中可以找到错误( http://msdn.microsoft.com/en-us/library/8ey5ey87 (VS.71).aspx ):

From the Class Library design guidelines for errors (http://msdn.microsoft.com/en-us/library/8ey5ey87(VS.71).aspx):


在大多数情况下,使用预定义的异常类型。仅为程序化方案定义新的异常类型,您期望类库的用户捕获此新类型的异常,并根据异常类型本身执行编程操作。这是代替解析异常字符串,这将对性能和维护造成负面影响。

In most cases, use the predefined exception types. Only define new exception types for programmatic scenarios, where you expect users of your class library to catch exceptions of this new type and perform a programmatic action based on the exception type itself. This is in lieu of parsing the exception string, which would negatively impact performance and maintenance.

...

如果传递或检测到无效参数,则抛出ArgumentException或创建从此类派生的异常。

Throw an ArgumentException or create an exception derived from this class if invalid parameters are passed or detected.

如果调用属性集访问器或方法时抛出InvalidOperationException异常不适合给定对象的当前状态。

Throw the InvalidOperationException exception if a call to a property set accessor or method is not appropriate given the object's current state.

这对我来说似乎是一个对象状态无效场景,所以我会选择InvalidOperationException over ArgumentException:参数是有效的,但不是在这一点上的对象生命。

This seems like an "Object state invalid" scenario to me, so I'd pick InvalidOperationException over ArgumentException: The parameters are valid, but not at this point in the objects life.

这篇关于当尝试将重复的对象插入集合时,什么是正确的.NET异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆