【发布时间】:2016-11-25 10:44:14
【问题描述】:
如标题中所述,我想知道是否有一种方法来约束属性,以便在将属性应用于错误的属性或方法时出现编译时错误(我希望这些属性将适用仅限于财产)。
例如:
[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!" ;
}
如果我可以约束我的属性,这样它们只能在实现特定接口(或从特定基类继承)的类中使用,那将是很好的选择。
【问题讨论】:
标签: c# constraints custom-attributes