我知道在 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/