使用属性作为属性参数
我编写了一个自定义信用卡验证属性,用于检查 CardNumber 属性对于特定卡类型(同一类中的另一个属性)是否有效。
[CardValidationBinCheck(this.CardType,
ErrorMessage = "CreditCardNumberDoesNotMatchCardType")]
public string CardNumber
{
...
}
这不会编译,因为工作室抱怨属性参数必须是常量、typeof 表达式或数组创建属性参数类型的表达式 (?)。
无论如何,我可以传递 cirvumvent 这个并将我的 this.CardType
传递给属性吗?
善良,
丹
I have written a custom credit card validation attribute that checks CardNumber property is valid for a particular card type (another property in the same class)
[CardValidationBinCheck(this.CardType,
ErrorMessage = "CreditCardNumberDoesNotMatchCardType")]
public string CardNumber
{
...
}
This won't compile as studio complains that attribute arguments must be constant, a typeof expression or an array creation expression of an attribute parameter type (?).
Is there anyway I can pass cirvumvent this and pass my this.CardType
to the attribute?
Kindness,
Dan
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不幸的是没有。即使 IL 允许属性值成为成员引用令牌(例如有效的
PropertyInfo
),也没有 C# 运算符可以为您获取一个成员引用令牌1。您可以将其作为字符串文字传递,然后使用反射来获取PropertyInfo
。丑陋且脆弱,但可能是你能得到的最接近的。1 这是一个众所周知的功能请求,可能称为“infoof”运算符。但没有任何迹象表明它正在实施。
Unfortunately not. Even if IL allows an attribute value to be a member reference token (e.g. a
PropertyInfo
effectively) there's no C# operator to get one for you1. You could pass it in as a string literal and then use reflection to get thePropertyInfo
though. Ugly and fragile, but probably the closest you'll get.1 This is a well-known feature request, possibly called the "infoof" operator. There's no sign of it being implemented though.