【问题标题】:How interface can be instantiate this way如何以这种方式实例化接口
【发布时间】:2014-02-20 09:03:09
【问题描述】:

从一个 url 我看到人们可以这样实例化界面

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); 寻求指导。谢谢

【问题讨论】:

  • 不是。我建议停止询问所有这些接口问题,并阅读一些关于 C# 中的接口和多态性的材料。
  • @Samuel 它确实有效。
  • 即使可能,这只会让整个interface 的想法变得毫无用处,最大的问题是:你为什么曾经想要这样做?
  • @dcastro 这对我来说确实是新的。托马斯请接受我对第一句话的道歉。我今天学到了一些新东西。除了 COM 特定属性之外,这不是处理接口时的常用方法。而且我仍然建议专注于基本接口概念的介绍。

标签: c# oop interface


【解决方案1】:

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

根据 C# 规范的 §17.5,System.Runtime.InteropServices 命名空间下的属性可能会违反所有规则。这是特定于 Microsoft 的 C# 实现的。

Marc Gravell 和 Jon Skeet 有非常好的博客文章:Who says you can’t instantiate an interface?Faking COM to fool the C# compiler

【讨论】:

    猜你喜欢
    • 2018-01-20
    • 1970-01-01
    • 2011-02-22
    • 2022-07-01
    • 1970-01-01
    • 2016-10-04
    • 1970-01-01
    • 2011-12-31
    • 1970-01-01
    相关资源
    最近更新 更多