谁能给我一个类型转换的定义,为什么以及什么时候我们应该使用它?
我试着在网上寻找材料,但找不到任何可以解释我们到底为什么需要类型转换以及什么时候使用它的东西。
举个例子就好了!
发布于 2012-01-07 00:26:19
类型转换是将对象强制转换为特定类型的机制。用外行的话来说,它就是从邮箱里拿起一封信(摘要),并强迫它成为一份账单(具体的,具体的)。
这在软件开发中通常是相关的,因为我们要处理大量的抽象,所以有时我们会检查给定对象的属性,而不能立即知道该对象的真正具体类型。
例如,在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,我将不得不将对象转换为更具体的对象。因此,例如,如果我知道对象是一个ArrayList,我可以将其转换为1:
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
}
}希望这有助于向您解释类型转换,以及为什么它是相关的,以及何时使用它!:)
https://stackoverflow.com/questions/8745696
复制相似问题