带变量的DisplayAttribute名称,动态DisplayName [英] DisplayAttribute name with a variable, Dynamic DisplayName

查看:469
本文介绍了带变量的DisplayAttribute名称,动态DisplayName的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想知道这是否可能或有这种效果。

 公共类MyModel 
{
公共字符串名称{get;组; }

[Display(Name = String.Format(这是[0]的电话号码,名称)]
公共字符串PhoneNumber {get; set;}
}

我说的是其中包含变量的DisplayName,它是非静态的,可能基于

解决方案

这是不可能的,因为必须为属性的参数指定参数是常量值(本能地,因为没有任何其他上下文,并且不一定能在编译时解析(这是必需的))。摘自C#Specification(3.0)§17.2:



如果满足以下所有条件,则表达式 E attribute-argument-expression : / p>


  • E 的类型是属性参数类型(第17.1.3节)。

  • 在编译时, E 的值可以解析为以下值之一:

    • 一个常数。

    • 一个System.Type对象。

    • 一个一维数组 attribute-argument-expressions 的类型。



Wondering if this is possible or something with this effect.

public class MyModel
{
    public string Name { get; set; }

    [Display(Name = String.Format("This is [0]'s phone number", Name)]
    public string PhoneNumber { get; set; }
}

I'm talking about a DisplayName with a variable in it, non static and possibly based on the models other properties. Is this possible in any way?

解决方案

This isn't possible because the arguments specified for parameters of attributes must be constant values (instinctively, because there is no context in relation to anything else and not necessarily able to be resolved at compile-time (which is a requirement)). From the C# Specification (3.0) §17.2:

An expression E is an attribute-argument-expression if all of the following statements are true:

  • The type of E is an attribute parameter type (§17.1.3).
  • At compile-time, the value of E can be resolved to one of the following:
    • A constant value.
    • A System.Type object.
    • A one-dimensional array of attribute-argument-expressions.

这篇关于带变量的DisplayAttribute名称,动态DisplayName的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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