简体   繁体   English

在foreach中未处理NullReference异常

[英]NullReference Exception was unhandled in foreach

An unhandled exception of type 'System.NullReferenceException' occurred in MyProject.exe MyProject.exe中发生了'System.NullReferenceException'类型的未处理异常
Additional information: Object reference not set to an instance of an object. 附加信息:对象引用未设置为对象的实例。

It says , StringCollection strCol is null, but table.Script() is not null (it includes the record). 它说, StringCollection strCol为null,但table.Script()不为null(包括记录)。 It does the foreach only once. 它仅执行一次foreach。 When it comes for a second time it gives this exception. 第二次出现此异常。 Here is my code: 这是我的代码:

foreach (var item in Sourceclb.Items)  
{
    Table table = database.Tables[item.ToString()];
    StringCollection strCol = table.Script();//Gives exception here
    var script = "";
    foreach (var key in strCol)
    {
         script += key;
    }
    command.Connection = ttbl;
    command.CommandText = "USE "+_hedefDb+" \n EXEC sp_sqlexec '"+scriptdondur(script)+ "'";

    command.ExecuteNonQuery();
    txtLog.AppendText("*TABLE COPIED* "+item.ToString()+" has been copied. \r\n");
}

I think you need to do 我认为你需要做

foreach (var item in database.Tables)

rather than 而不是

foreach (var item in Sourceclb.Items)

Not all the items in Sourceclb.Items will be tables, and as soon as you hit one that isn't, database.Tables[item.ToString()] will return null, with the consequent NullReferenceException at table.Script() . 并非Sourceclb.Items所有项目Sourceclb.Items将是表,一旦您击中不存在的项目, database.Tables[item.ToString()]将返回null,并因此在table.Script()处返回NullReferenceException。

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

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