接口如何以这种方式实例化 [英] How interface can be instantiate this way

查看:135
本文介绍了接口如何以这种方式实例化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从网址看到人们可以像这样实例化界面

from a url i saw people can instantiate interface like this way

class Program
{
    static void Main(string[] args)
    {
        var foo = new IFoo(1);
        foo.Do();
    }
}

[
    ComImport, 
    Guid("C906C002-B214-40d7-8941-F223868B39A5"), 
    CoClass(typeof(FooImpl))
]
public interface IFoo
{
    void Do();
}

public class FooImpl : IFoo
{
    private readonly int i;

    public FooImpl(int i)
    {
        this.i = i;
    }

    public void Do()
    {
        Console.WriteLine(i);   
    }
}

如何写这样的 var foo = new IFoo(1); 寻找指导。谢谢

how it is possible to write like this var foo = new IFoo(1); looking for guidance. thanks

推荐答案

这就是COM的工作原理。您已将 FooImpl 声明为 IFoo 的coclass。 new IFoo(1); 将编译为 new FooImpl(1);

That's just how COM works. You've declared FooImpl to be IFoo's coclass. new IFoo(1); will be compiled to new FooImpl(1);

根据C#规范的第17.5节, System.Runtime.InteropServices 命名空间下的属性可能会破坏所有规则。这是微软C#实现的特定内容。

According to §17.5 of the C# specification, attributes under the System.Runtime.InteropServices namespace may break all the rules. This is specific to Microsoft's C# implementation.

Marc Gravell和Jon Skeet关于此的博客文章非常好:谁说你无法实例化界面?伪造COM来欺骗C#编译器

Marc Gravell and Jon Skeet have really good blog posts about this: Who says you can’t instantiate an interface? and Faking COM to fool the C# compiler

这篇关于接口如何以这种方式实例化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆