2012-01-05 201 views
2

任何人都可以給我一個類型鑄造的定義以及爲什麼以及何時應該使用它?類型鑄造和類型轉換

我試着在網上尋找材料,但找不到任何能解釋我爲什麼我們需要類型轉換以及何時使用它的內容。

一個例子會很棒!

+3

我們在討論哪種語言? – 2012-01-05 16:10:49

+1

-0。廣泛的,你可以在谷歌上輸入的東西。我不想因此而失敗。 – Gabe 2012-01-05 16:12:06

+0

我敢肯定,你只會失去點投票答案,而不是問題。 – 2012-01-05 16:16:52

回答

1

類型轉換是強制對象成爲特定類型的機制。通俗地說,它是從信箱中挑選一封信(摘要),並將其強制成賬單(具體的,具體的)。

這通常與軟件開發有關,因爲我們處理大量的抽象,所以有時我們會檢查給定對象的屬性,而不立即知道所述對象的真實具體類型。

在C#中,例如我可能對檢查鏈接到特定控件的數據源的內容感興趣。

object data = comboBox.DataSource; 

的.DataSource屬性的類型是「對象」(在C#是抽象的,你可以得到)的,這是因爲DataSource屬性支持多種不同的具體類型,並希望允許程序員從多種類型中選擇使用。

所以,回到我的檢查。使用這種對象類型,我可以用「對象數據」做很多事情。

data.GetType();  // tells me what type it actually is 
data.ToString(); // typically just outputs the name of the type in string form, might be overridden though 
data.GetHashCode(); // this is just something that gets used when the object is put in a hashtable 
data.Equals(x);  // asks if the object is the same one as x 

這是因爲這些是在C#中的類對象上定義的唯一API。爲了訪問更有趣的API,我將不得不將對象轉換爲更具體的對象。 所以,如果,例如我知道對象是一個ArrayList的,我可以將它轉換爲一個:

ArrayList list = (ArrayList) data; 

現在我可以用一個ArrayList的API(如果轉換工作)。所以我可以做這樣的事情:

list.Count; // returns the number of items in the list 
list[x]; // accesses a specific item in the list where x is an integer 

我在上面演示的演員是所謂的「硬」演員。它將對象強制轉換爲我想要的任何數據類型,並且(在C#中)在轉換失敗時拋出異常。所以通常你只想在100%確定對象是或應該是那種類型時使用它。

C#還支持所謂的「軟」轉換,如果轉換失敗則返回null。

ArrayList list = data as ArrayList; 
if(list != null) 
{ 
    // cast worked 
} 
else 
{ 
    // cast failed 
} 

當您不太確定類型並且想要支持多種類型時,您會使用軟轉換。

可以說你是comboBox類的作者。在這種情況下,你可能要支持不同類型的.DataSource的所以你最好使用軟石膏支持許多不同的類型可能會寫代碼:

public object DataSource 
{ 
    set 
    { 
    object newDataSource = value; 
    ArrayList list = newDataSource as ArrayList; 
    if(list != null) 
    { 
     // fill combobox with contents of the list 
    } 
    DataTable table = newDataSource as DataTable; 
    if(table != null) 
    { 
     // fill combobox with contents of the datatable 
    } 
    // etc 
    } 
} 

希望幫助解釋類型轉換到你,爲什麼它是有關以及何時使用它!:)