gpt4 book ai didi

c# - MVC5/C# - 无法对空引用执行运行时绑定(bind)

转载 作者:行者123 更新时间:2023-12-03 00:35:34 25 4
gpt4 key购买 nike

我试图找出导致此代码出现 Cannot Perform Run Run Runtime Binding on a null Reference 错误的原因:

var query = "SELECT Id, UserName, List_Order, LoggedIn " + 
"FROM AspNetUsers" +
"WHERE LoggedIn = 1" +
"ORDER BY List_Order ASC";

var conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
var cmd = new SqlCommand(query, conn);
conn.Open();
var rdr = cmd.ExecuteReader();
var n = 0;
while(rdr.Read())
{
if (Convert.ToString(rdr["UserName"]) != null)
{
ViewBag.speakers[n] = new string[4] {
Convert.ToString(rdr["Id"]),
Convert.ToString(rdr["UserName"]),
Convert.ToString(rdr["List_Order"]),
Convert.ToString(rdr["LoggedIn"])
};

//Exception Details: Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: Cannot
//perform runtime binding on a null reference
n++;
}
}

n++ 增量似乎是此错误的原因,我不明白为什么。

更新了代码以反射(reflect)可能的解决方案。但是,错误仍然存​​在。

尝试了同样的结果:

if (!string.IsNullOrWhiteSpace(Convert.ToString(rdr["UserName"]))) {
List<string> speakers = new List<string>();
speakers.Add(Convert.ToString(rdr["Id"]));
speakers.Add(Convert.ToString(rdr["UserName"]));
speakers.Add(Convert.ToString(rdr["List_Order"]));
speakers.Add(Convert.ToString(rdr["LoggedIn"]));

ViewBag.speakers[n] = speakers;
n++;
}

最佳答案

您的代码中有两个问题:

考虑一下:

public ActionResult Index()
{
int n = 0;
ViewBag.speakers[n] = 5;
return View();
}

这段简化的代码抛出 Cannot perform runtime binding on a null reference因为未定义扬声器(空引用)。

您可以通过定义 speakers 来修复它在循环之前的动态 ViewBag 中:

ViewBag.speakers = new List<string>();

第二期:

ViewBag.speakers[n] = speakers;

代码中的speakers是一个List,你可能需要定义ViewBag.speakers作为List<List<string>>并调用.Add(speakers)而不是使用索引进行访问(您可能会得到索引超出范围)

关于c# - MVC5/C# - 无法对空引用执行运行时绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40531522/

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