【问题标题】:Difference Between ToString() and Casting to StringToString() 和强制转换为字符串之间的区别
【发布时间】:2015-10-18 15:29:28
【问题描述】:
string id = (string)result.Rows[0]["Id"];

上面的代码行返回InvalidCastException。为什么会这样?

但是,如果我将代码更改为此

string id = result.Rows[0]["Id"].ToString();

那么它就可以工作了。我在上一行代码中做错了吗?

【问题讨论】:

标签: c# string casting


【解决方案1】:

它不起作用,因为ID 有不同的类型。这不是string - 所以你可以转换它但不能转换它。

【讨论】:

    【解决方案2】:

    ToString() 不只是转换你的对象,它调用它的ToString 方法提供一个“字符串表示”。然而,投射意味着对象本身是一个字符串,因此您可以投射它。

    也可以看看这里:Casting to string versus calling ToString

    编辑:从object 派生的ToString-方法可用于表示任意对象。

    MyClass 
    {
        int myInt = 3;
        public override string ToString() {
            return Convert.ToString(myInt);
        }
    }
    

    如果ToString 在你的类中没有被覆盖,那么它的默认返回值就是类的类型名。

    【讨论】:

      【解决方案3】:

      使用 ToString() 您将 row0 的 Id 转换为字符串,但在其他情况下,您将转换为字符串,这在当前场景中是不可能的。

      【讨论】:

        【解决方案4】:

        我猜你的行的索引器类型不是string。演员表如下所示:

        (TypeA)objB
        

        只有在

        时才会成功
        1. objB 的类型为TypeA

        2. objBTypeC 类型,其中TypeCTypeA 的子类,

        3. objBTypeC 类型,其中TypeCTypeA 的超类,objB 的声明类型是TypeA

        所以,您的代码不起作用。

        然而,由于每种类型都派生自神圣的Object 类,因此每种类型都有一个ToString 方法。因此,无论Rows[0]["Id"] 返回什么类型,它都有或没有ToString 方法的自定义实现。 ToString 方法的返回值的类型总是,你猜对了,String。这就是ToString 起作用的原因。

        【讨论】:

          【解决方案5】:

          让我们看看不同的操作,比如你和编译器之间的对话:

              // here you say to compiler "hey i am 100% sure that it is possible 
              // to cast this `result.Rows[0]["Id]` to string
              // this results in error if cast operation failed
          
              string id = (string)result.Rows[0]["Id"];
          
          
              // here you say to compiler: "please try to cast it to 
              // string but be careful as i am unsure that this is possible"
              // this results in `null` if cast operation failed
          
              string id = result.Rows[0]["Id"] as string;
          
          
              // here you say to compiler: "please show me the string representation of 
              // this result.Rows[0]["Id"] or whatever it is"
              // this results in invoking object.ToString() method if type of result.Rows[0]["Id"]  
              // does not override .ToString() method.
          
              string id = result.Rows[0]["Id"].ToString();
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2011-05-19
            • 2014-09-30
            • 2011-03-30
            • 1970-01-01
            相关资源
            最近更新 更多