约束属性给定类型的属性

时间:2016-11-25 10:44:15

标签: c# constraints custom-attributes

如标题中所述,我想知道是否存在约束属性的方法,以便在将属性应用于错误属性或方法时出现编译时错误(我希望这些属性适用仅限于财产)。

例如:

[StringAttribute(..something)]
public string  MyStringPropery { get; set; } //<-- ok pass compile time constraint

[StringAttribute(..something)]
public int MyIntProperty { get; set; } //<-- throw error at compile time for type missmatch (that attribute will apply only to string not int)

[StringAttribute(..something)]
public string SayHello ()  //<-- throw error at compile time, that attribute apply only to property not method
{
    return "Hello!" ;
}

如果我可以约束我的属性以便它们只能在实现特定接口的类中使用(或继承形成特定的基类),则可以选择。

1 个答案:

答案 0 :(得分:1)

由于您无法访问附加属性的成员,因此无法在编译时检查属性的类型。此外,编译器实际上不会实例化您的属性或在其上运行代码。它只会将其添加到程序集元数据中。编译器运行其内置检查,您无法扩展。

但是可以在属性定义中对属性进行限制:

[AttributeUsage(AttributeTargets.Property)]
public class StringAttribute : Attribute
{
    //Attribute definition
}