How interface can be instantiate this way

自古美人都是妖i 提交于 2019-12-11 10:34:13

问题


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);   
    }
}

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


回答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);

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 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



来源:https://stackoverflow.com/questions/21902878/how-interface-can-be-instantiate-this-way

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!