MVC5 / C#-无法对空引用执行运行时绑定 [英] MVC5 / C# - Cannot perform runtime binding on a null reference

查看:726
本文介绍了MVC5 / C#-无法对空引用执行运行时绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找出是什么原因导致无法对空引用执行运行时绑定来自以下代码的错误:

I'm trying to figure out what's causing a Cannot perform runtime binding on a null reference error from this code:

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 ++ 增量似乎是导致此错误的原因,我不明白为什么。

The n++ increment seems to be the cause of this error and I don't understand why.

已更新代码以反映可能的解决方案。但是,错误仍然存​​在。

Updated code to reflect possible solutions. However, the error still remains.

尝试了相同的结果:

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();
}

这段简化的代码抛出无法执行运行时绑定

This simplified piece of code throws Cannot perform runtime binding on a null reference since speakers is not defined (null reference).

您可以通过定义 speakers 在循环前的 dynamic ViewBag中:

You can fix it by defining speakers in the dynamic ViewBag before the loop:

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

第二期:

ViewBag.speakers[n] = speakers;

在代码中的发言人是一个列表,您可能想定义 ViewBag。发言者作为 List< List< string>> 并调用。添加(发言人)而不是使用索引进行访问(您可能会得到索引超出范围

speakers in your code is a List, you might want to define ViewBag.speakers as a List<List<string>> and call .Add(speakers) instead of accessing using an index (you might get index was out of range)

这篇关于MVC5 / C#-无法对空引用执行运行时绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆