将对象强制转换为KeyValuePair引发异常

本文关键字:KeyValuePair 异常 转换 对象 | 更新日期: 2023-09-27 18:22:26

我有一个asp.net应用程序,它有一个接收包含键值<string,string>集合的对象参数的函数,我想将这些对象强制转换为keyValuePair <string,string>.

这是我的代码:

[WebMethod]
public static string ProcessIT(object employeeDts1, string val)
{
      KeyValuePair<string, string> txt = new KeyValuePair<string, string>();
      txt = ( KeyValuePair<string, string>)employeeDts1 ;
      if (txt!=null)
      {
          //here I process that object...
      }
}

但问题是,当我将该对象转换为Keyvaluepair时,我得到了以下错误

"指定的强制转换无效。"

将对象强制转换为KeyValuePair引发异常

您说过它是KeyValuePair的集合,所以您当然不能将该集合强制转换为KeyValuePair的单个实例。

你要么想创建另一个集合,要么只从那个集合中提取一个——是哪个?

public static string ProcessIT(object employeeDts1, string val)
{
      // cast object to concrete type, assuming collection is IEnumerable here
      // but obviously only you know what the type is
      var KvpCollection = employeeDts1 As IEnumerable<KeyValuePair<string,string>>;
      if (KvpCollection == null) 
        {
           // bad data, you better handle it and not carry on
        }
      foreach (var keyValuePair in KvpCollection)
      {
        // do something to each of your keyValuePair objects ...
      }
}