其实我工作的一个框架的发展,这意味着需要一个真正强大的编码方法。
I am actually working on a Framework development, which means require a really strong coding methodology.
我现在面临一个问题,我不知道我需要抛出该System.Exception的推导类。基本上的情况是,当我有一个类,可以通过构造函数初始化optionnaly领域,并且在使用这些字段的方法。其中的例外,我必须抛出,如果用户没有初始化这些领域? (这意味着它们是空的)
I am facing a problem where I do not know which System.Exception derivated class I need to throw. Basically the case is when I have a class with fields that can be optionnaly initialized by the constructor and that have methods using these fields. Which exception must I throw if the user did not initialized these fields? (which means they are null)
下面是一个例子:
public class MyConnection
{
private Uri endpointUri;
public Uri EndpointUri
{
get
{
return this.endpointUri;
}
set
{
this.endpointUri = value;
}
}
public MyConnection()
{
}
public MyConnection(Uri endpointUri)
{
this.endpointUri = endpointUri;
}
public FileStream GetFile()
{
if (this.endpointUri != null)
{
// My doer methods
}
else
{
throw new TheExceptionINeedToThrow("endpointUri", ...);
}
}
}
请注意,我一直在阅读章关于异常处理和抛出和整个框架设计指南我没有找到任何解决办法配合这个确切的情况。或者,也许我误解了什么......
Note that I have been reading the whole "Framework Design Guidelines" chapter concerning exception handling and throwing and that I did not found any solution fitting this exact case. Or maybe I misunderstood something ...
感谢您的帮助。
编辑:我提供了一个空的构造的事实似乎有点混乱关于我的问题,但它是完全自愿的。在此必须遵守各种不同的状态,不能在多个对象有时是有用的复制某些对象。
EDIT : The fact that I provide an empty constructor seems a bit confusing regarding my problem but it is completely voluntary. In some objects that have to comply with a range of different states that cannot be duplicated in multiple objects it is sometimes useful.
投掷InvalidOperationException:
例外,当一个方法调用对于对象的当前状态无效时引发。
The exception that is thrown when a method call is invalid for the object's current state.
需要注意的是空引用的不是的被传递到方法 - 它已经存在时,该方法被调用 - 因此它的对象的当前状态,这是无效的,没有一个参数。
Note that the null reference isn't being passed into the method - it's already there when the method is called - so it's the object's current state which is invalid, not an argument.
不过,这将是更好的prevent从以这种方式开始与正在创建的对象,如果在所有可能的 - 它的有无的可写性?难道你会希望有一个实例,它的没有的有一个空的端点URI?
However, it would be better to prevent the object from being created in this way to start with, if at all possible - does it have to be a writable property? Would you ever want an instance which did have a null endpoint URI?
上一篇:发现使用LINQ最小和最大日期数组?数组、最小、日期、发现
下一篇:Environment.CurrentDirectory和Directory.GetCurrentDirectory之间的区别是什么?区别、CurrentDirectory、Environment、G