gpt4 book ai didi

c# - 重载构造函数时如何避免 NullReferenceException?

转载 作者:行者123 更新时间:2023-11-30 20:34:09 25 4
gpt4 key购买 nike

为了更好地解释我的情况,我编了一个例子

void Main()
{
var a = new Lol(null);
}

public class Lol
{
public Lol(string a, string b)
{
if(a == null || b == null)
{
throw new Exception();
}
}

public Lol(Tuple<string, string> k)
: this(k.Item1, k.Item2)
{
}
}

在这种情况下,我在第二个构造函数中得到一个 NullReferenceException。有没有办法从方法内部处理它,保持相同的结构,或者我应该创建一个私有(private)方法并让两个构造函数都调用这个方法?

最佳答案

您可以将逻辑抽象为辅助方法,并让两个构造函数都调用该辅助方法。

public class Lol
{
public Lol(string a, string b)
{
LolHelper(a, b);
}

public Lol(Tuple<string, string> k)
{
(k!=null)
?LolHelper(k.Item1, k.Item2)
:LolHelper(null, null);
}

private void LolHelper(string a, string b)
{
if(a == null || b == null)
{
throw new Exception();
}
}
}

关于c# - 重载构造函数时如何避免 NullReferenceException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39573889/

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