4

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

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

Shell32.Shell是来自“shell32.dll”的接口

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

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

更新:

为了使它工作,我只需要添加ComImport属性并更改 co-class(我不能选择 Shell32.ShellClass)。

多谢你们!

4

2 回答 2

2

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

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

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

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

[除了 CoClassAttribute,您]需要 ComImportAttribute 和 GuidAttribute 才能使其工作

于 2018-10-09T16:13:50.850 回答
1

如果您在 Visual Studio 中右键单击 Shell32.Shell 并转到定义,您将获得以下接口定义:

using System.Runtime.InteropServices;

namespace Shell32
{
    [CoClass(typeof(ShellClass))]
    [Guid("286E6F1B-7113-4355-9562-96B7E9D64C54")]
    public interface Shell : IShellDispatch6
    {
    }
}

在 ShellClass 上执行相同的操作,您将获得在代码中创建的具体类:

Shell32.Shell shObj = new Shell32.Shell();
于 2018-10-09T15:59:49.107 回答