gpt4 book ai didi

c# - 如何初始化一个接口(interface)?

转载 作者:行者123 更新时间:2023-12-04 13:30:21 26 4
gpt4 key购买 nike

到目前为止我学到的是我们不能创建接口(interface)的实例。

    interface IFood
{
string Color { get; set; }
}
class Apple : IFood
{
public string Color { get ; set; }
}
IFood food = new IFood(); //this gives compile error IFood food = new Apple(); //this will work
到这里为止一切都还好。但是当我使用 Microsoft.Office.Interop.Excel我见过类似下面的东西
Application excel = new Application();// Application is an interface
我在这里想念什么?

Meta data of Application interface

最佳答案

这是 COM 的互操作能力
Microsoft.Office.Excel API 包括 Application类,是用 C++ 编写的

由于 C++ 中的架构更自由,在某些情况下需要初始化接口(interface)

.

.NET 使用 CoClass COM 对象上的属性以解决启动接口(interface)

C# 不允许启动接口(interface),但使用 CoClass属性,接口(interface)初始化可以路由到类CoClass
(示例代码值(value)千字)所以让我们重现这个解决方法:

[CoClass(typeof(SugarGlider))] 
[ComImport] // pretend as a COM class
[Guid("000208D5-0000-0000-C000-000000000046")] // put it randomly just to fool the ComImport
public interface ISquirrel
{
string Foo();
}

[ClassInterface(ClassInterfaceType.None)]
public class SugarGlider : ISquirrel
{
public string Foo(){ return "Bar"; }
}

您现在可以通过 new ISquirrel() 启动界面

完整示例并在线运行: https://rextester.com/ORAZQ51751

关于c# - 如何初始化一个接口(interface)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59539798/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com