ToString()和强制转换为字符串之间的区别
本文关键字:字符串 之间 区别 转换 ToString | 更新日期: 2023-09-27 18:04:57
string id = (string)result.Rows[0]["Id"];
上面的代码行返回InvalidCastException
。为什么会这样?
但如果我将代码更改为string id = result.Rows[0]["Id"].ToString();
,那么它就可以工作了。我在前一行代码中做错了什么吗?
它不起作用,因为ID
具有不同的类型。它不是string
,所以您可以转换它,但不能强制转换它。
让我们看看不同的操作,比如你和编译器之间的对话:
// 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();
我猜您的行索引器的类型不是string
。演员阵容如下:
(TypeA)objB
只有当
objB
属于TypeA
型,objB
是类型TypeC
,其中TypeC
是TypeA
的子类,objB
是类型TypeC
,其中TypeC
是TypeA
的超类,objB的声明类型是TypeA
。
所以,您的代码不起作用。
但是,由于每个类型都派生自神圣的Object
类,因此每个类型都有一个ToString
方法。因此,无论返回什么类型的Rows[0]["Id"]
,它都有或没有ToString
方法的自定义实现。ToString
方法的返回值的类型总是,您猜到了,String
。这就是ToString
工作的原因。
ToString()
不是简单地强制转换对象,它调用其ToString
方法,提供"字符串表示"。然而,铸造意味着物体本身是一根绳子,因此你可以铸造它
还可以看看这里:强制转换为字符串与调用ToString
EDIT:从object
派生的ToString
方法可以用来表示任何任意对象。
MyClass
{
int myInt = 3;
public override string ToString() {
return Convert.ToString(myInt);
}
}
如果ToString
没有在类中重写,那么它的默认返回值是类的typename。
使用ToString((,您将row0的Id转换为字符串,但在其他情况下,您将转换为字符串——这在当前场景中是不可能的。