限制自定义属性,以便它只能应用于C#中的特定类型? [英] Restrict custom attribute so that it can be applied only to Specific types in C#?

查看:97
本文介绍了限制自定义属性,以便它只能应用于C#中的特定类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义属性,它应用于类属性和类本身。现在,必须应用我的自定义属性的所有类都派生自一个基类。

I have a custom attribute which is applied to class properties and the class itself. Now all the classes that must apply my custom attribute are derived from a single base class.

如何限制我的自定义属性,以便它只能应用于那些类,那必须来自我的基类?我该怎么做?

How can I restrict my Custom Attribute so that it can be applied to only those classes, that must derive from my base class? How do I do this?

推荐答案

Darn,我讨厌当我证明自己错了......如果你定义了属性为受保护的基类的嵌套类型:

Darn, I hate it when I prove myself wrong... it works if you define the attribute as a protected nested type of the base-class:

abstract class MyBase {
    [AttributeUsage(AttributeTargets.Property)]
    protected sealed class SpecialAttribute : Attribute {}
}

class ShouldBeValid : MyBase {
    [Special]
    public int Foo { get; set; }
}
class ShouldBeInvalid {
    [Special] // type or namespace not found
    [MyBase.Special] // inaccessible due to protection level
    public int Bar{ get; set; }
}






(原始答案)


(original answer)

你不能这样做 - 至少,不是在编译时。

You cannot do this - at least, not at compile time.

属性可以被限制(例如)到类,结构,方法,字段等 - 但没有更精细。

Attributes can be restricted (for exmaple) to "class", "struct", "method", "field", etc - but nothing more granular.

当然,因为属性本​​身不做任何事情(忽略PostSharp),它们对其他类型是惰性的(并且对你的类型不敏感,除非你在运行时添加一些代码来查看属性)。

Of course, since attributes do nothing by themselves (ignoring PostSharp), they will be inert on other types (and inert on your types unless you add some code to look at the attributes at runtime).

你可以写一个FxCop规则,但这似乎有点矫枉过正。

You could write an FxCop rule, but that seems overkill.

但我想知道属性是否是最佳选择:

I wonder, however, whether an attribute is the best choice:


现在所有必须应用我的自定义属性的类都派生自一个基类。

Now all the classes that must apply my custom attribute are derived from a single base class.

如果他们必须应用您的自定义属性,可能是 abstract (或者只是虚拟)属性/方法会是更好的选择吗?

If they must apply your custom attribute, maybe an abstract (or maybe just virtual) property / method would be a better choice?

abstract class MyBase {
    protected abstract string GetSomeMagicValue {get;}
}
class MyActualType : MyBase {
    protected override string GetSomeMagicValue {get {return "Foo";}}
}

这篇关于限制自定义属性,以便它只能应用于C#中的特定类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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