开发者

What's the need of marker interface when Attributes serve the purpose?

I'm a bit confused about

The purpose of开发者_开发百科 Marker Interface Vs Attributes.

Their purpose looks same to me(Pardon me if I'm wrong).

Can anyone please explain how do they differ in purpose?


Here are some advantages of both.

Marker interfaces:

  • are a bit easier to check for using dynamic type checks (´obj is IMarker´);
  • allow for functional and data extensibility in the future (i.e. turning a “marker” interface into a “full” interface that actually declares some members);
  • can be used in generic type constraints;

On the other hand, attributes:

  • provide a clearer separation of metadata;
  • allow for specifying additional information via their constructors or properties;
  • allow for multiple application to an entity;
  • are general-purpose in terms of applicability to different kinds of entities, not just classes;

It heavily depends on the particular application's architecture and design whether it's appropriate to use a marker interface or an attribute in a particular case.


Some years ago, in the pre Java 5 era, Java didn't support attributes. Therefore, to "tag" a class or an interface so that they could be checked at runtime, you would use marker interfaces, which is basically an empty interface but you can still check if an instance can be casted to this interface.

In .NET, marker interfaces should not be used except for special use cases (such as allowing the use of extension methods), because attributes provide a better way to mark classes (and lots more) with metainformation. The same goes for Java 5 and newer, where annotations were introduced and should be used instead.


If you can use it, an Attribute is preferred.

But there are a few features related to static typing only an interface can offer:

  1. You can add extension methods to it
  2. You can use it as a generic constraint


As an aside, it is much quicker to check for an interface, as the CLI is designed for that and has opcodes for it (as does c#: is/as).

Checking attributes requires reflection; much slower.

Looking though the other answers most points are covered, but also: attributes are much more limited in terms of what values you can pass into them; mainly primitives and string.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜