在进行向上或向下转换时,幕后究竟发生了什么?我的想法是,在做某事时:
string myString = "abc";
object myObject = myString;
string myStringBack = (string)myObject;
最后一行中的强制转换的唯一目的是告诉编译器我们是安全的,我们没有做错任何事情。所以,我的想法是,实际上不会在代码本身中嵌入任何转换代码。看来我错了:
.maxstack 1
.locals init (
[0] string myString,
[1] object myObject,
[2] string myStringBack)
L_0000: nop
L_0001: ldstr "abc"
L_0006: stloc.0
L_0007: ldloc.0
L_0008: stloc.1
L_0009: ldloc.1
L_000a: castclass string
L_000f: stloc.2
L_0010: ret
为什么 CLR 需要类似的东西castclass string
?
向下转换有两种可能的实现:
- 您需要一个
castclass something
. 当您到达执行 的代码行时,castclass
CLR 会尝试进行强制转换。但是,如果我省略了 castclass 字符串行并尝试运行代码会发生什么? - 您不需要
castclass
. 由于所有引用类型都具有相似的内部结构,如果您尝试在 Form 实例上使用字符串,它将抛出错误使用异常(因为它检测到 Form 不是字符串或其任何子类型)。
此外,简而言之,C# 4.0 中的以下陈述是否正确?
Upcasting and downcasting between compatible reference types performs reference
conversions: a new reference is created that points to the same object.
它真的创造了一个新的参考吗?我认为这将是相同的引用,只是存储在不同类型的变量中。
谢谢