gpt4 book ai didi

c# - NullReferenceException 错误 C#

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

这个问题在这里已经有了答案:





What is a NullReferenceException, and how do I fix it?

(27 个回答)


8年前关闭。



        QueryClass Query;
string UserName = "";
int UserId = 0;


string email = txtEmail.Text;
string name = txtUserName.Text;
string phone = txtPhone.Text;
byte[] buffer = new byte[100];

UserName = Query.GetUserName(email); //returns a string value

if (UserName != null)
{
MessageBox.Show(UserName + " is already in the database");
}

if (Query.AddNewUser(name, email, phone) == true) //returns a bool value
{
UserId = Query.GetUserId(email); //returns a int value
if (Query.AddNewImage(UserId, buffer) == true) //returns a bool value
{
MessageBox.Show("Done..!!");
}

}

MessageBox.Show("Error");

单击程序的插入按钮(代码上方)后,出现以下错误。
System.NullReferenceException
Message="Object reference not set to an instance of an object."

我在以下地方遇到了这个异常(exception)。 (我没有检查其他地方)代码只是停止这些地方并给出错误。
UserName = Query.GetUserName(email); //returns a string value

if (Query.AddNewUser(name, email, phone) == true) //returns a bool value

谁能帮我解决这个错误?我正在使用 Visual Studio 2010。

最佳答案

您正在使用 Query没有实际将其设置为任何东西。您可能需要构建一个实例:

// Change: QueryClass Query;
QueryClass Query = new QueryClass();

在不创建实例的情况下,当您调用时:
 UserName = Query.GetUserName(email);

此时, Query仍然是默认值(对于引用类型是 null),你会得到 NullReferenceException在尝试使用它时。

附带说明一下,您可能需要考虑将此变量命名为 query (小写)和类 Query (或者,更好的是,一个更具描述性的名称),以便遵循正常的 .NET 命名准则。

关于c# - NullReferenceException 错误 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16570829/

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