How interface can be instantiate this way

2019-08-05 10:28发布

问题:

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



标签: c# oop interface