铸造类型&类型转换

时间:2012-01-05 16:09:39

标签: type-conversion

有人能给我一个关于类型转换的定义以及为什么以及何时应该使用它?

我尝试在线寻找资料,但找不到任何可以解释我为什么需要进行类型转换以及何时使用它的内容。

一个例子很棒!

2 个答案:

答案 0 :(得分:1)

类型转换是将对象强制转换为特定类型的机制。通俗地说,它正在从邮箱中取出一封信(摘要)并强制将其写入账单(具体的,具体的)。

这通常与软件开发相关,因为我们处理大量抽象,因此有时我们会检查给定对象的属性而不是立即知道所述对象的真实具体类型。

例如,在C#中,我可能有兴趣检查链接到特定控件的数据源的内容。

object data = comboBox.DataSource;

.DataSource属性的类型为“object”(在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,我将不得不将对象CAST更具体。 因此,如果我知道对象是一个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
  }
}

希望这有助于向您解释类型转换及其相关性以及何时使用它! :)

答案 1 :(得分:0)

维基百科有一篇关于不同类型的好文章。 http://en.wikipedia.org/wiki/Cast_(computer_science)

相关问题