到目前为止,我学到的是我们无法创建接口的实例。
interface IFood
{
string Color { get; set; }
}
class Apple : IFood
{
public string Color { get ; set; }
}
Run Code Online (Sandbox Code Playgroud)
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
我在这里缺少什么?
nyc*_*ing 10
这是 COM 的互操作能力
Microsoft.Office.ExcelAPI 包括Application类,都是用 C++ 编写的
由于 C++ 中的架构更自由,在某些情况下需要初始化接口
.
.NET 使用CoClassCOM 对象上的属性来解决启动接口的方法
C#不允许初始化接口,但是通过CoClass属性,接口初始化可以路由到类CoClass
(价值一千字的示例代码)所以让我们重现这个解决方法:
[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"; }
}
Run Code Online (Sandbox Code Playgroud)
您现在可以通过以下方式启动界面new ISquirrel()
完整示例并在线运行:https : //rextester.com/ORAZQ51751