什么是空接口用于 [英] What is an empty interface used for

查看:25
本文介绍了什么是空接口用于的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在看 nServiceBus 并从这个接口过来

I am looking at nServiceBus and came over this interface

namespace NServiceBus
{
    public interface IMessage
    {
    }
}

空接口有什么用?

推荐答案

通常用于表示类的使用.您可以实现 IMessage 以表明您的类是一条消息.然后其他代码可以使用反射来查看您的对象是否打算用作消息并采取相应的行动.

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.

在Java有注解之前,这个东西已经在Java中使用了很多.在 .Net 中,为此使用属性更干净.

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 谢谢!我没有那样想过.我希望您能允许我以更笼统的方式重新表述您的评论.

@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.

这篇关于什么是空接口用于的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆