![](/img/trans.png)
[英]Is there a difference between the ToString method and casting to string?
[英]Difference Between ToString() and Casting to String
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
編輯:從object
派生的ToString
方法可用於提供任何任意對象的表示形式。
MyClass
{
int myInt = 3;
public override string ToString() {
return Convert.ToString(myInt);
}
}
如果您的類中沒有重寫ToString
則默認的返回值是類的類型名。
使用ToString(),您可以將row0的ID轉換為字符串,但在其他情況下,則將其轉換為字符串,這在當前情況下是不可能的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.