据我所知,如果我们正在处理 COM
接口(interface),任何简单的转换通常都会触发 QueryInterface
例程,用于确定对象是否实际实现了相应的 COM
界面。
object whatever;
IComInterface casted = (IComInterface) whatever;
因此,根据编译器和优化,以下代码可能会触发 QueryInterface
在内部对象转换实现中:
IComInterface comInteface;
// I guess nothing COM-related happens here, but I might be wrong
object whatever = comInteface;
// This might or might not trigger the 'QueryInterface' call.
IComInterface comInterface2 = (IComInteface) whatever;
问:
假设我有一个通用的 List<T>
实例:
List<IComInterface> list = new List<IComInterface>();
现在,我是否可以强有力地保证以下代码不会触发 QueryInterface
基于类型转换?
List<IComInterface> list = new List<IComInterface>();
IComInterface comInterface = (...); // Somehow got it.
list.Add(comInteface);
IComInterface retrieved = list[0];
使用
ArrayList
而不是List<T>
这里实际上导致执行转换,因为你必须得到相应的IComInterface
来自你的无类型object
实例。但是,如果是泛型,我想一切都应该在没有转换的情况下完成,但我实际上不确定它们在表面下是如何工作的。
有没有可能
List<T>
仍然以某种方式与object
一起运行类型(因此,将在所述场景中调用基于QueryInterface
的转换)?如果对上一个问题的回答是“否”,那么您是否不能保证任何可能的
IList<T>
都相同? ?
最佳答案
您可以将通用类型实例(例如 List<IComInterface>
)视为从通用类型定义(例如 List<T>
)创建的类,方法是将名称 T
逐字替换为名称 IComInterface
.该类型不会像在某些语言(最值得注意的是 Java)中那样被“删除”,它与泛型类型实例一起保存,因此在泛型类型定义中声明为类型 T
的所有变量在泛型中保持强类型类型实例。
在 List<IComInterface>
的情况下,只要您在编译时插入已知为 object
类型的对象,就不会转换为 IComInterface
或从 ojit_code 转换。您帖子中的代码就是这种情况,但可能并不总是如此。例如,当你插入一个动态类型的对象时,编译器会添加一个强制转换:
dynamic comInteface = ...
list.Add(comInteface); // There will be an implicit cast here
关于C# - <T> 对象转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11451614/