【问题标题】:difference between type conversion and type casting? [duplicate]类型转换和类型转换的区别? [复制]
【发布时间】:2026-01-27 07:15:01
【问题描述】:

可能重复:
What is the difference between casting and conversion?

类型转换和类型转换的区别? ii 举个例子就更好了..

【问题讨论】:

    标签: .net c#-4.0


    【解决方案1】:

    首先,这是

    的副本

    What is the difference between casting and conversion?

    灵感来自

    What is the (type) in (type)objectname.var

    我会先阅读这些内容,然后再回到这个简短的摘要。

    请参阅规范第 6 章的第一段,其中指出:

    转换使表达式能够 被视为特定的 类型。转换可能会导致 给定类型的表达式为 被视为具有不同的类型,或 它可能会导致没有 a 的表达式 type 获取类型。转换可以 隐式或显式,而这 确定显式转换是否是 必需的。例如,转换 从 int 类型到 long 类型是 隐式的,所以 int 类型的表达式 可以隐式地被视为类型 长。相反的转换,从 键入 long 以键入 int,是显式的并且 所以需要一个明确的演员表。

    我们从中学到了什么?

    • 转换是对两个操作数的语义操作表达式类型

    • 语义分析确定的确切操作决定了实际值在运行时如何转换。

    • cast(type)expression 形式的 C# 语言的 句法元素,它显式地从类型的表达式。

    这些只是您可以在 C# 中进行的一些隐式转换:

    short aa = 123;      // numeric constant conversion from int to short
    int bb = aa;         // numeric conversion from short to int
    int? cc = null;      // nullable conversion from null literal to nullable int.
    object dd = "hello"; // implicit reference conversion from string to object
    IEnumerable<Giraffe> ee = new Giraffe[] { new Giraffe() } ;
                         // implicit reference conversion from array to sequence
    IEnumerable<Animal> ff = ee; 
                         // implicit reference conversion involving array covariance
    ff = null;           // implicit reference conversion from null literal to sequence
    bb = 456;            // implicit identity conversion from int to int
    dd = bb;             // implicit boxing conversion from int to object
    Func<int, int> gg = x=>x+x; 
                         // anonymous function to delegate type conversion 
    

    显式转换通常但并非总是需要强制转换:

    aa = (short)bb;      // explicit numeric conversion
    string hh = (string)dd; //explicit reference conversion
    

    等等。

    合法使用强制转换进行隐式转换,但通常没有必要。

    清楚吗?关键是转换是一种语义操作,它会导致运行时的动作,而强制转换是告诉编译器分析转换的句法元素使用显式转换分析规则

    如果您对转换逻辑的主题感兴趣,那么您可能会对我关于该主题的文章感兴趣,这些文章在这里:

    http://blogs.msdn.com/b/ericlippert/archive/tags/conversions/

    【讨论】:

    • “显式转换通常但不总是需要强制转换”:你能举一个不需要强制转换的例子吗?在我的脑海中,我想不出任何......
    • @Thomas: foreach(Giraffe g in animals) 诱导从 Animal 到 Giraffe 的显式转换,无需演员表。字节 b = 1; b += 2;诱导从 int 到 byte 的显式转换;这被分析为 b = (byte)((int)b+(int)1))。作为用户定义的显式转换的强制转换可能会在操作数的“任一侧”引入内置的显式转换;在这种情况下,我们确实在源代码中进行了强制转换,但它可能导致最多三个显式转换实际执行。
    • 还有一些晦涩的互操作场景,其中编译器会代表您插入从接口到类的显式转换。
    • 感谢您提供的示例。顺便说一句非常有趣的答案!
    【解决方案2】:

    转换 = 实际上将对象转换为不同类的实例 例如:

    int i = 3; 
    string str = i.ToString();
    

    将整数转换为字符串

    强制转换 = 强制对象的类型,因为你比编译器知道的更多 例如:

    object obj = 3;
    int i = (int)obj;
    

    【讨论】:

      【解决方案3】:

      Here 是一个很好的线程,其中包含一些示例和对您问题的回答。

      【讨论】: