简体   繁体   English

无法将类型为'System.Object []'的对象强制转换为'System.String []'

[英]Unable to cast object of type 'System.Object[]' to type 'System.String[]'

I am developing a C# VS 2008 / SQL Server website application. 我正在开发一个C#VS 2008 / SQL Server网站应用程序。 I am a newbie to ASP.NET. 我是ASP.NET的新手。 I am getting the above error, however, on the last line of the following code. 但是,我在以下代码的最后一行收到了上述错误。 Can you give me advice on how to fix this? 你能给我一些如何解决这个问题的建议吗? This compiles correctly, but I encounter this error after running it. 这编译正确,但运行后遇到此错误。

All that I am trying to do is to store the items from the second row of "dt" into string parameters. 我想要做的就是将第二行“dt”中的项目存储到字符串参数中。 The first row is the header, so I don't want these values. 第一行是标题,所以我不想要这些值。 The second row is the first row of values. 第二行是第一行值。 My SQL stored procedure requires these values as strings. 我的SQL存储过程需要将这些值作为字符串。 So I want to parse the second row of data and load into 2 string parameters. 所以我想解析第二行数据并加载到2个字符串参数中。 I added more of my code below. 我在下面添加了更多代码。

DataTable dt; 
Hashtable ht;
string[] SingleRow;
...
SqlConnection conn2 = new SqlConnection(connString);
SqlCommand cmd = conn2.CreateCommand();
cmd.CommandText = "dbo.AppendDataCT";
cmd.Connection = conn2;
SingleRow = (string[])dt.Rows[1].ItemArray;
            SqlParameter sqlParam = cmd.Parameters.AddWithValue("@" + ht[0], SingleRow[0]);
            sqlParam.SqlDbType = SqlDbType.VarChar;
            SqlParameter sqlParam2 = cmd.Parameters.AddWithValue("@" + ht[1], SingleRow[1]);
            sqlParam2.SqlDbType = SqlDbType.DateTime;

My error: 我的错误:

System.InvalidCastException was caught
  Message="Unable to cast object of type 'System.Object[]' to type 'System.String[]'."
  Source="App_Code.g68pyuml"
  StackTrace:
       at ADONET_namespace.ADONET_methods.AppendDataCT(DataTable dt, Hashtable ht) in c:\Documents and Settings\Admin\My Documents\Visual Studio 2008\WebSites\Jerry\App_Code\ADONET methods.cs:line 88
  InnerException: 

You can't cast an array of objects into an array of strings, you have to cast each item in the array, as each items has to be checked if it can be cast. 您不能将对象数组转换为字符串数组,您必须在数组中转换每个项目,因为必须检查每个项目是否可以转换。 You can use the Cast method for that: 您可以使用Cast方法:

SingleRow = dt.Rows[1].ItemArray.Cast<string>().ToArray();
string[] arr = Array.ConvertAll(dt.Rows[1].ItemArray, o => (string)o);

(你也可以使用Cast<T>().ToArray() ,但这种方法适用于更多的框架版本,并从一开始就获得正确的数组大小,而不是调整它的大小)

Hmmm. 嗯。 You're trying to access properties of the DataTable dt , but it looks like you might be expecting that table to contain the results of the AppendDataCT query. 您正在尝试访问DataTable dt属性,但看起来您可能希望该表包含AppendDataCT查询的结果。 It doesn't. 它没有。 Be careful with your row index accesses, too: Arrays in C# are 0-based, and dt.Rows[1] will retrieve the second row in the table. 小心你的行索引访问:C#中的数组是从0开始的,而dt.Rows[1]将检索表中的第二行。

That aside, review the documentation for DataRow.ItemArray . 除此之外,请查看DataRow.ItemArray的文档。 That method returns an array of objects, not an array of strings. 该方法返回一个对象数组,而不是一个字符串数组。 Even if your row contains nothing but strings, you're still dealing with an array of objects, and you'll have to treat it that way. 即使你的行只包含字符串,你仍然在处理一系列对象,你将不得不这样对待它。 You can cast each individual item in the row to a string, if that's the proper datatype for that column: 您可以将行中的每个单独项目转换为字符串,如果这是该列的正确数据类型:

foreach (string s in dt.Rows[1].ItemArray)
{
  //...
}

EDIT : Ok, in response to your edit, I see what you're trying to do. 编辑 :好的,为了回应您的编辑,我看到您正在尝试做什么。 There are many different ways to do this, and I'd particularly recommend that you move away from HashTables and towards generic equivalents like Dictionary - you'll save yourself much runtime casting grief. 有很多不同的方法可以做到这一点,我特别建议你从HashTables转向像Dictionary这样的通用等价物 - 你将节省很多运行时的铸造悲伤。 That said, here's the simplest adaption of your code: 也就是说,这是您的代码最简单的适应:

DataRow dr = dt.Rows[1]; // second row
SqlParameter p1 = cmd.Parameters.AddWithValue((string)ht[0], (string)dr[0]);
SqlParameter p2 = ...

You don't need the leading "@"; 你不需要领先的“@”; ADO.NET will add that for you. ADO.NET将为您添加。 The (string) casts will work as long as there's a string at key 0 (which is a fairly non-standard way to use hashtables - you'd usually have some kind of descriptive key), and if the first column in your datatable contains strings. 只要键0处有一个字符串(这是一种使用哈希表的相当非标准的方法 - 你通常会有某种描述性键),并且如果数据表中的第一列包含,那么(字符串)强制转换就会起作用字符串。

I recommend you look at typed datasets and generic collections . 我建议您查看类型化数据集泛型集合 The lack of them here makes your code somewhat brittle. 这里缺少它们会使您的代码变得有些脆弱。

Each column item have it's own type, that can be different from String, so if you want to store each row value into an array you have to do it one-by-one with a loop, or with LINQ (I haven't tested this snippet but should do it's job): 每个列项都有自己的类型,可以与String不同,所以如果你想将每个行值存储到一个数组中,你必须逐个循环,或者使用LINQ(我还没有测试过)这个片段,但应该做它的工作):

(from columnVal in dt.Rows[1].ItemArray
select columnVal.ToString()).ToArray();

You can use LINQ for that: 您可以使用LINQ:

var yourStringArray = dt.Rows[1].ItemArray
    .Select(o => (o ?? (object)String.Emtpy).ToString())
    .ToArray();

This converts each item of the array to a string by using ToString() and returns an empty string if the item is null. 这会使用ToString()将数组的每个项转换为字符串,如果该项为null,则返回空字符串。

How about this: make string[] SingleRow into object[] SingleRow , which will let the line 怎么样:make string[] SingleRow into object[] SingleRow ,这将让行

SingleRow = (object[])dt.Rows[1].ItemArray;

execute properly. 正确执行。 Subsequently when you need to access its values as an array of strings, cast it or LINQ select it like this: 随后,当您需要将其值作为字符串数组访问时,将其强制转换或LINQ选择它如下:

objectArray.Select<object, string>
   (c => (c != null ? c.ToString() : "")).ToArray();

Make sure to add the following usings: 确保添加以下用法:

using System.Linq;
using System.Collections.Generic;

暂无
暂无

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

相关问题 无法将类型“ System.String”强制转换为类型“ System.Object” - Unable to cast the type 'System.String' to type 'System.Object' 多维数组转换运行时错误---&gt;无法将类型为&#39;System.Object [,]&#39;的对象转换为&#39;System.String类型 - Multidimensional Array Casting Runtime Error ---> unable to cast object of type 'System.Object[,]' to type 'System.String 无法将类型“ System.String”强制转换为类型“ System.Object”。 LINQ to Entities仅支持转换实体数据模型原语类型 - Unable to cast the type 'System.String' to type 'System.Object'. LINQ to Entities only supports casting Entity Data Model primitive types 从动态集合创建地图不再有效:无法将 System.String 类型的 object 转换为 System.Object) - Create maps from dynamic collection no longer works: Unable to cast object of type System.String to System.Object) 无法将“System.String”类型的对象转换为“System.Collections.Generic.List`1[System.String]”类型 - Unable to cast object of type 'System.String' to type 'System.Collections.Generic.List`1[System.String]' 无法将“ System.Object []”转换为类型“ System.String []” - Cannot convert 'System.Object[]' to the type 'System.String[]' 无法将类型类的对象强制转换为“ System.String”类型 - Unable to cast object of type class to type 'System.String' 无法将“DapperRow”类型的对象转换为“System.String”类型 - Unable to cast object of type 'DapperRow' to type 'System.String' 无法将“System.string”类型的对象转换为“....Event”类型 - Unable to cast object of type 'System.string' to type '....Event' 无法将“AttachmentDetailsDto”类型的对象转换为“System.String”类型 - Unable to cast object of type 'AttachmentDetailsDto' to type 'System.String'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM