我可以创建一个用于属性参数的常量表达式吗? [英] Can I create a constant expression for use in attribute parameter?

查看:61
本文介绍了我可以创建一个用于属性参数的常量表达式吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何回答此问题的人都知道,属性的参数需要常量表达式。可选参数(对于任何东西,不仅是属性)还需要使用常量表达式作为其默认值。

As anyone answering this already knows, parameters of attributes require constant expressions. Optional parameters (for anything, not just attributes) also require constant expressions for their default values.

<$ c $给我带来的(虽然是次要的)不便c> RegularExpressionAttribute 的pattern参数。我的数据模型中有数十个使用此属性的属性(可在System.ComponentModel.DataAnnotations中找到),每当更改验证模式时,都必须返回并进行 everryyywherrreee 。 。 。

The (albeit minor) inconvenience I'm having is with RegularExpressionAttribute's pattern parameter. I have dozens of properties in my data-model that use this attribute (found in System.ComponentModel.DataAnnotations), and whenever I make a change to the validation pattern, I have to go back and make that change everryyywherrreee . . . it's really quite annoying.

是否可以声明.net结构并将其识别为常量表达式,然后在通常需要常量表达式的情况下可用?

Is there a .net structure that can be declared, recognized as a constant expression, and then be usable where constant expressions are normally required?

如果我可以声明 RegexPatternForNameProperty = ^ [a-zA-Z0-9,。#] {1,150} $ 属性,然后根据需要更改该值。

It would be great if I could just declare a RegexPatternForNameProperty = "^[a-zA-Z0-9,.# ]{1,150}$" property somewhere, then just change that one value as needed.

推荐答案

任何可定义为<$ c的内容$ c> const 可以在属性中使用。因此,您仍然受限于编译时常量,但不必直接使用字符串或数字值。

Anything that can be defined as a const can be used in an attribute. So you are still limited to compile-time constants, but you do not have to use string or numeric values directly.

public const string RegexPatternForNameProperty = "^[a-zA-Z0-9,.# ]{1,150}$";

[RegularExpression(RegexPatternForNameProperty)]
public string Name {get; set;}

这篇关于我可以创建一个用于属性参数的常量表达式吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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