How to define the default implementation of an interface in c#?

前端 未结 3 1366
刺人心
刺人心 2020-12-28 14:17

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

So you can write

var instance = new ISomeInterf         


        
3条回答
  •  别那么骄傲
    2020-12-28 15:18

    Here comes the black magic:

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

提交回复
热议问题