如何定义在C#接口的默认实现?接口、定义

2023-09-02 12:02:50 作者:差不多先生℡

有一些黑魔法code在C#中,你可以定义一个接口的默认实现。

There is some black magic code in c# where you can define the default implementation of an interface.

所以,你可以写

var instance = new ISomeInterface();

任何指针?

更新1:请注意,是没有问,如果这是一个好主意。只是怎么可能做到这一点。

UPDATE 1: Note that is did not ask if this is a good idea. Just how was it possible to do it.

更新2:给任何人看接受的答案

在这应该仅仅被视为一种好奇心。从马克碎石http://stackoverflow.com/questions/1303717/newing-up-interfaces 在这是一个坏主意,使用专为COM的工具互操作完全和完全不同的做一些事情。这使得你的code无法理解谁拥有维持其未来的家伙,从埃里克利珀http://stackoverflow.com/questions/1303717/newing-up-interfaces 虽然它可能工作,如果它是迄今发现的生产code。通过合理的codeR,它会进行重构使用一个基类或依赖注入来代替。从斯蒂芬·克利在下面留言。 "this should be treated merely as a curiosity." from Marc Gravel http://stackoverflow.com/questions/1303717/newing-up-interfaces "It's a bad idea to use a tool designed for COM interop to do something completely and utterly different. That makes your code impossible to understand for the next guy who has to maintain it" from Eric Lippert http://stackoverflow.com/questions/1303717/newing-up-interfaces "While it may work, if it were ever found in production code by a rational coder, it would be refactored to use a base class or dependency injection instead." from Stephen Cleary in a comment below.

推荐答案

这里来的黑魔法:

class Program
{
    static void Main()
    {
        IFoo foo = new IFoo("black magic");
        foo.Bar();
    }
}

[ComImport]
[Guid("C8AEBD72-8CAF-43B0-8507-FAB55C937E8A")]
[CoClass(typeof(FooImpl))]
public interface IFoo
{
    void Bar();
}

public class FooImpl : IFoo
{
    private readonly string _text;
    public FooImpl(string text)
    {
        _text = text;
    }

    public void Bar()
    {
        Console.WriteLine(_text);
    }
}

请注意,您不仅可以实例化一个接口,但也传递参数给它的构造函数: - )

Notice that not only you can instantiate an interface but also pass arguments to its constructor :-)