数据类型之间的转换可以使用强制转换显式进行,但在某些情况下,也允许隐式转换。例如:

C# CopyCode image复制代码
static void TestCasting()
{
    int i = 10;
    float f = 0;
    f = i;  // An implicit conversion, no data will be lost.
    f = 0.5F;
    i = (int) f;  // An explicit conversion. Information will be lost.
}

显式强制转换调用转换运算符,从一种类型转换为另一种类型。如果未定义相应的转换运算符,则强制转换会失败。可以编写自定义转换运算符,在用户定义类型之间进行转换。有关定义转换运算符的更多信息,请参见 explicit(C# 参考)implicit(C# 参考)

Expand 图像示例

Expand 图像输出

Expand 图像C# 语言规范

Expand image请参见