接口或属性标记类? [英] Interfaces or Attributes for Tagging Classes?

查看:126
本文介绍了接口或属性标记类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个,我希望与特定属性标记类。我想到的两种方法。一包括使用一延伸属性类。另使用一个空接口:

I have a couple of classes that I wish to tag with a particular attribute. I have two approaches in mind. One involves using an Attribute-extending class. The other uses an empty interface:

属性

public class FoodAttribute : Attribute { }

[Food]
public class Pizza { /* ... */ }

[Food]
public class Pancake { /* ... */ }

if (obj.IsDefined(typeof(FoodAttribute), false)) { /* ... */ }

接口

public interface IFoodTag { }

public class Pizza : IFoodTag { /* ... */ }
public class Pancake : IFoodTag { /* ... */ }

if (obj is IFoodTag) { /* ... */ }

我犹豫要使用的属性由于反思其使用。与此同时,但是,我在创建时只有真正作为标签的空接口犹豫不决。我已经压力测试都和这两者之间的时间差仅约为3毫秒,所以性能不受到威胁这里。

I'm hesitant to use the attributes due to its usage of Reflection. At the same time, however, I'm hesitant on creating an empty interface that is only really serving as a tag. I've stress-tested both and the time difference between the two is only about three milliseconds, so performance is not at stake here.

推荐答案

那么,与属性,可以总是以这样一种方式,其功能不会传播自动后代类型创建属性。

Well, with attributes, you can always create the attribute in such a way that its function doesn't propagate to descendant types automatically.

使用的接口,这是不可能的。

With interfaces, that's not possible.

我会去与属性。

这篇关于接口或属性标记类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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