What is an empty interface used for

后端 未结 12 2712
醉话见心
醉话见心 2020-12-13 17:18

I am looking at nServiceBus and came over this interface

namespace NServiceBus
{
    public interface IMessage
    {
    }
}

What is the us

12条回答
  •  遥遥无期
    2020-12-13 18:02

    Usually it's to signal usage of a class. You can implement IMessage to signal that your class is a message. Other code can then use reflection to see if your objects are meant to be used as messages and act accordingly.

    This is something that was used in Java a lot before they had annotations. In .Net it's cleaner to use attributes for this.


    @Stimpy77 Thanks! I hadn't thought of it that way. I hope you'll allow me to rephrase your comment in a more general way.

    Annotations and attributes have to be checked at runtime using reflection. Empty interfaces can be checked at compile-time using the type-system in the compiler. This brings no overhead at runtime at all so it is faster.

提交回复
热议问题