C# 如何在调用其他构造函数之前引发ArgumentNullException
我有一个关于构造函数语法和在构造函数中抛出异常的问题 如何在调用CreateAnotherOne()之前为参数b抛出ArgumentNullException,并像在第二个构造函数中一样抛出异常,而不在检查后重复代码?我可以将代码提取到一个单独的私有方法中,但我需要从两个构造函数体调用它。。。有没有其他办法来实现这一点C# 如何在调用其他构造函数之前引发ArgumentNullException,c#,syntax,exception-handling,constructor,C#,Syntax,Exception Handling,Constructor,我有一个关于构造函数语法和在构造函数中抛出异常的问题 如何在调用CreateAnotherOne()之前为参数b抛出ArgumentNullException,并像在第二个构造函数中一样抛出异常,而不在检查后重复代码?我可以将代码提取到一个单独的私有方法中,但我需要从两个构造函数体调用它。。。有没有其他办法来实现这一点 public class MyClass { public MyClass(IWhatEver a, ISomeThingElse b) : this(a
public class MyClass
{
public MyClass(IWhatEver a, ISomeThingElse b)
: this(a, b != null ? b.CreateAnotherOne() : null)
{
// or should I call :this(a, b.CreateAnotherOne()) instead? this could cause a NullReferenceException => how to verify that b is not null?
// don't want to call CallMeFromConstructor() instead of call to other constructor
// would not do the following (why should I check a/c twice?) and the check is too late here (because already called a method on b, b.CreateAnotherOne())
if (a == null)
{
throw new ArgumentNullException("a");
}
if (b == null)
{
throw new ArgumentNullException("b");
}
}
public MyClass(IWhatEver c, IAnotherOne d)
{
if (c == null)
{
throw new ArgumentNullException("c");
}
if (d == null)
{
throw new ArgumentNullException("d");
}
// the cool code comes here, I could put it into
// the CallMeFromConstructor method but is there another way?
}
...
private void CallMeFromConstructors()
{
// the cool code could be here, too (but is there another way?)
}
如果我用:this(a,b!=null?b.CreateAnotherOne():null)调用第二个构造函数,我将在第二个构造函数中得到d的ArgumentNullException。这对我来说听起来很奇怪,可能会产生误导,因为我调用了第一个(只能在堆栈跟踪中看到)
问题是我不会写字
:this(a, b == null ? b.CreateAnotherOne() : throw new ArgumentNullException("b"));
如果我把检查放在构造函数的主体中,在这种情况下,它会被检查到很晚
有什么好办法可以解决这个问题吗?一个私有方法可以解决这个问题,但您也可以创建另一个私有构造函数:
private MyClass(IWhatEver a)
{
if (a == null)
{
throw new ArgumentNullException("a");
}
// the cool code comes here, I could put it into
// the CallMeFromConstructor method but is there another way?
}
public MyClass(IWhatEver a, ISomeThingElse b) : this(a)
{
if (b == null)
{
throw new ArgumentNullException("b");
}
}
public MyClass(IWhatEver a, IAnotherOne b) : this(a)
{
if (b == null)
{
throw new ArgumentNullException("b");
}
}
//或者我应该叫这个(a,b)来代替?这就是我要做的不清楚你想要什么。你能描述你想要的行为,而不是描述构造函数吗?@Haxx不能这样做,因为第二个参数是另一个类型的好主意,这可以防止代码被调用两次,thx