【问题标题】:Bool to string in C#?在 C# 中布尔到字符串?
【发布时间】:2014-01-12 21:31:39
【问题描述】:

我运行我的 C# 应用程序,它很大,所以我只包含了一部分代码

我的代码:

allowGift = Convert.ToInt32(dRow[14]) == 1;
allowInventoryStack = Convert.ToInt32(dRow[15]) == 1;
interactionType = InterractionTypes.GetTypeFromString((string)dRow[16]); //Line of error

以及堆栈跟踪的错误

System.InvalidCastException:无法将类型为“System.Boolean”的对象转换为类型“System.String”

【问题讨论】:

  • dRow的类型是什么? interactionType 的类型是什么?是哪一行导致了错误?
  • 您似乎在使用this class。虽然下面的大多数答案都是善意的,但它们不会起作用,因为InteractionType 没有从True 或False 转换。很抱歉,根据您提供给我们的信息,您的问题无法回答。
  • 查看InteractionType 枚举(包括“football”、“teleport”和“firegate”等值),并确保您传递给GetTypeFromString 的值是在那里。

标签: c# string boolean


【解决方案1】:

而不是这个:

(string)dRow[16]

试试ToString:

dRow[16].ToString()

或Convert.ToString:

Convert.ToString(dRow[16])

【讨论】:

    【解决方案2】:

    改变这一行:

    interactionType = InterractionTypes.GetTypeFromString((string)dRow[16]); //Line of error
    

    到这里:

    interactionType = InterractionTypes.GetTypeFromString(dRow[16].ToString()); //Line of error
    

    【讨论】:

    • 解析代码中未知的交互类型:False System.InvalidCastException:指定的强制转换无效
    • 请查看@Michael Petrotta cmets 了解您的问题。此错误与您的问题无关,即如何将布尔值转换为字符串。此错误是由于使用了您正在使用的 InterractionTypes 库,它不接受 False 作为有效输入值。
    【解决方案3】:

    bool 不能直接转换为需要转换的string。您可以像在代码中其他地方所做的那样使用 Converter 类

    InterractionTypes.GetTypeFromString(Convert.ToString(dRow[16]));
    

    【讨论】:

      【解决方案4】:

      用dRow[16].ToString()代替(string)dRow[16]

      【讨论】:

      • 解析代码中未知的交互类型:False System.InvalidCastException:指定的强制转换无效
      猜你喜欢
      • 2015-02-07
      • 2010-10-04
      • 2013-06-13
      • 2012-08-10
      • 1970-01-01
      • 2016-01-12
      • 2023-03-29
      • 2018-09-10
      • 2015-11-30
      相关资源
      最近更新 更多