简体   繁体   English

在代码运行时从头开始创建数组

[英]Creating an array from scratch while code is running

I am trying to create a list via array like this: 我试图通过像这样的数组创建列表:

private Application[] GetApps()
{
DataSet ds = new Dataset();
string query = "query";
ds = GetData(query);

var appList = new Application[ds.Tables[0].Rows.Count];

for(var i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
                DataRow item = ds.Tables[0].Rows[i];

                appList[i].Name = item["Name"].ToString();
                appList[i].Confidentiality = int.Parse(item["Conf"].ToString());
                appList[i].Id = item["ID"].ToString();
}
return appList;
}

I keep getting an object null error and I know I have to be missing something completely obvious that I'm just not seeing. 我不断收到一个对象为null的错误,并且我知道我必须丢失一些完全看不见的东西。 Do I need to declare the new array in some other way? 我是否需要以其他方式声明新数组?

When you create appList , you are only creating the array itself. 创建appList ,您仅创建数组本身。 .NET does not automatically populate the array with Application objects for you to manipulate. .NET不会自动使用应用程序对象填充数组供您操作。 You need to create a new Application object, and set the properties on that object, then you can assign the object to the array. 您需要创建一个新的Application对象,并在该对象上设置属性,然后可以将该对象分配给数组。

There are multiple Application classes withing the .NET framework, none of which seem to match your code, so the below example will simply assume that Application is a custom type of your own design. .NET框架中有多个Application类,它们似乎都不与您的代码匹配,因此下面的示例将简单地假定Application是您自己设计的自定义类型。

for(var i = 0; i < ds.Tables[0].Rows.Count; i++)
{
    DataRow item = ds.Tables[0].Rows[i];

    Appliction app = new Application();
    app.Name = item["Name"].ToString();
    app.Confidentiality = int.Parse(item["Conf"].ToString());
    app.Id = item["ID"].ToString();
    appList[i] = app
}

As an aside, note that you can replace i <= x - 1 with i < x and the behavior is exactly the same. 顺便说一句,请注意,您可以将i <= x - 1替换为i < x ,并且行为完全相同。

Finally, you should introduce checks for all of your accessors if there is a chance that they could return null. 最后,如果所有访问器都可能返回null,则应该对其进行检查。 For example, if item["Name"] returns null, then calling item["Name"].ToString() is equivelant to calling null.ToString() , which will also result in a NullReferenceException . 例如,如果item["Name"]返回null,则调用item["Name"].ToString()等同于调用null.ToString() ,这也会导致NullReferenceException

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM