限制自定义属性,以便它可以在C#仅应用于Specifc类型? [英] Restrict custom attribute so that it can be applied only to Specifc types in C#?

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

问题描述

我这是适用于类属性和类本身的自定义属性。现在一切都必须申请我的自定义属性的类是从单个基类派生的。

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, 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; }
}



(原来的答案)

您不能做到这一点 - 至少,不能在编译时间

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),他们将(除非你添加一些code看在运行时的属性和惰性你的类型)是对其他类型的惰性。

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.

如果他们的必须应用您的自定义属性,也许一个摘要(或者只是虚拟)属性/方法将是一个更好的选择?

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#仅应用于Specifc类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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