c# - 为什么 C# 允许从 "new Shell32.Shell()"中的接口(interface)构造对象?

标签 c# interface shell32.dll

我知道在 C# 中,您通常不能创建抽象类或接口(interface)的实例。谁能帮我理解这段代码(它编译没有任何错误)。

Shell32.Shell shObj = new Shell32.Shell();

Shell32.Shell 是 'shell32.dll' 的接口(interface)

我尝试了以下方法,但它没有编译:

[CoClass(typeof(ShellClass))]
[Guid("286E6F1B-7113-4355-9562-96B7E9D64C54")]
public interface OtherShell : Shell
{
}
OtherShell shObj = new OtherShell();

更新:

为了让它工作,我只需要添加 ComImport 属性并更改共同类(我不能选择 Shell32.ShellClass)。

谢谢大家!

最佳答案

除了所有其他信息之外,这里是如何生成编译代码的。接口(interface)的使用仅仅是代码的精巧。

IL_000c: newobj       instance void [Interop.Shell32]Shell32.ShellClass::.ctor()

也就是说,它是基于 [CoClass] 属性从接口(interface)“到”类的编译时转换。

根据 https://stackoverflow.com/a/1094140/2864740 ,它显示了一个最小的示例案例:

[In addition to CoClassAttribute, you] need both the ComImportAttribute and the GuidAttribute for it to work.

关于c# - 为什么 C# 允许从 "new Shell32.Shell()"中的接口(interface)构造对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52724916/

相关文章:

c# - 使用 LINQ 读取 xml 并存储在对象列表中

go - 接口(interface)类型转换不起作用

c++ - Linux 中的语音到文本转换

.net - 如何解决 windows-10 webbrowser shellfolderview 滚动错误?

c# - SqlDataReader.Read() 在 C# 中始终为 false

c# - 发送和接收 UDP 数据包

java - 'instanceof' 运算符对接口(interface)和类的行为不同

c# Shell32 压缩/解压缩代码,CopyHere 不起作用

C# lambda 引用输出