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

查看:7
本文介绍了限制自定义属性,使其只能应用于 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?

推荐答案

该死,当我证明自己错了时,我讨厌它...如果您将属性定义为 protected 嵌套类型基类:

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(或者可能只是 virtual)属性/方法会是更好的选择?

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天全站免登陆