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

前端 未结 3 1367
刺人心
刺人心 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:02

    Only if ISomeInterface is a class.

    Update (for clarification):

    Jon Skeet has a talk where he mentions default implementations for interfaces. They are not part of the C# language, though. The talk is about what Jon Skeet would like to see in a future version of C#.

    For now, the only default implementations are done via (possibly abstract) base classes.

    0 讨论(0)
  • 2020-12-28 15:06

    Maybe you refer to Dependency Injection? Where when using DI framework (such as Ninject or Unity), you can define default instance for each interface and then using it like this:

    (assuming you have IWeapon interface and Sword implements it)

    IKernel kernel = new StandardKernel();
    kernel.Bind<IWeapon>().To<Sword>();
    var weapon = kernel.Get<IWeapon>();
    

    But Ninject (and most other IoC frameworks) can do some more clever things, like: let's say we have the class Warrior that takes IWeapon as a parameter in its constructor. We can get an instance of Warrior from Ninject:

    var warrior = kernel.Get<Warrior>();
    

    Ninject will pass the IWeapon implementation we specified to the Warrior constructor method and return the new instance.

    Other than that, I don't know of any in-language feature that allows this kind of behavior.

    0 讨论(0)
  • 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 :-)

    0 讨论(0)
提交回复
热议问题