【问题标题】:Unable to cast object of type 'System.Int16' to type 'System.String'无法将“System.Int16”类型的对象转换为“System.String”类型
【发布时间】:2013-08-26 10:59:09
【问题描述】:

我在 LINQ 查询中遇到以下异常。

无法将“System.Int16”类型的对象转换为“System.String”类型。


 var query = from t in dt.AsEnumerable()
                        select new
                        {
                            sys_db= t.Field<Int16>("process_id").ToString() + "|" + t.Field<string>("db_code").ToString(),
                            process_name = t.Field<string>("process_name").ToString()
                        };

为什么会出现这个问题以及如何解决?

【问题讨论】:

  • sys_db= t.Field("process_id").ToString() + "|" + t.Field("db_code").ToString(), 你为什么写 Int16?因为您需要更改为字符串......因为文本正在合并
  • 您的db_codeint 的类型
  • Specified cast is not valid.
  • “db_code”字段的数据类型是什么?它必须是 Int16

标签: c# asp.net linq casting .net


【解决方案1】:

这个

t.Field<string>("db_code").ToString()

也许应该是这样的:

t.Field<short>("db_code").ToString()

或同等的

t.Field<Int16>("db_code").ToString()

【讨论】:

    【解决方案2】:

    为什么会出现这个问题

    这是因为您试图将 Int16 字段读取为字符串,这是不允许的

    如何解决

    首先确定实际上是 int16 的字段,并且您正在读取为字符串。从您的代码来看,很可能是这个字段

    t.Field<string>("db_code")
    

    你需要把它改成

    t.Field<Int16>("db_code")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-09-07
      • 2014-03-14
      • 2017-11-24
      • 1970-01-01
      • 2023-04-03
      • 2021-04-26
      相关资源
      最近更新 更多