gpt4 book ai didi

C# 对象引用未设置为对象的实例

转载 作者:太空宇宙 更新时间:2023-11-03 18:42:57 25 4
gpt4 key购买 nike

我有以下代码:

public void SetUser(User user)
{
string streetNumber = "";

if (user.Address.StreetNo != null)
streetNumber = user.Address.StreetNo.ToString();
else
streetNumber = "";
}

我得到了永远流行

Object reference not set to an instance of an object.

问题。

最佳答案

public void SetUser(User user)
{
string streetNumber = "";

if (user != null && user.Address != null && user.Address.StreetNo != null) {
streetNumber = user.Address.StreetNo.ToString();
}
}

考虑到@CKoenig 的建议,如果 useruser.Addressnull,则以下抛出异常:

public void SetUser(User user)
{

if (user == null) {
throw new System.ArgumentNullException("user", "user cannot be null");
}

if (user.Address == null) {
throw new System.ArgumentNullException("Address", "Address cannot be null");
}

string streetNumber = "";

if (user.Address.StreetNo != null) {
streetNumber = user.Address.StreetNo.ToString();
}
}

关于C# 对象引用未设置为对象的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7118779/

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