DisplayAttribute name with a variable, Dynamic DisplayName

我是研究僧i 提交于 2019-12-01 16:40:00

问题


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?


回答1:


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.



回答2:


For purposes like internationalisation, you can subclass the key attributes like DisplayNameAttribute, DescriptionAttribute and CategoryAttribute, and use some lookup (resx, database, whatever). This works fine and it is easy to find examples.

However, you cannot access values of the object, simply because: an attribute is not given that context!

However, if this is for things like PropertyGrid, DataGridView etc, there is another approach: use either ICustomTypeDescriptor or TypeDescriptionProvider to provide a custom descriptor, which can specify the DisplayName it wants. You can capture the target object/property when you create the instance of the custom descriptor. If you only want to tweak the properties, sometimes TypeConverter can be simpler to implement than ICustomTypeDescriptor/TypeDescriptionProvider, but ultimately both need custom PropertyDescriptor implementations.

This is all quite a bit of work; make sure you're happy with this level of complexity! There is probably a simpler option.



来源:https://stackoverflow.com/questions/9434918/displayattribute-name-with-a-variable-dynamic-displayname

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!