使用属性作为属性参数

发布于 2024-08-04 12:03:10 字数 402 浏览 5 评论 0原文

我编写了一个自定义信用卡验证属性,用于检查 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

泪之魂 2024-08-11 12:03:10

不幸的是没有。即使 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 the PropertyInfo 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文