C# 为什么我能';是否将DisplayAttribute与全局资源文件一起使用?

C# 为什么我能';是否将DisplayAttribute与全局资源文件一起使用?,c#,asp.net,resources,C#,Asp.net,Resources,这个问题已经解释了我想做什么,下面是一个例子: [Display(Name = Localization.City)] public string City { get; set; } 错误是,但(对我来说)没有意义:属性参数必须是常量表达式、typeof表达式或属性参数类型的数组创建表达式。错误消息很清楚 本地化。城市不是常数。我假设它只是一个静态的“只读”字段/属性。属性参数必须在编译时固定。 请参考Jon Skeet关于SO的回答: 表达式E是一个属性参数表达式,如果 以下语句为>tru

这个问题已经解释了我想做什么,下面是一个例子:

[Display(Name = Localization.City)]
public string City { get; set; }

错误是,但(对我来说)没有意义:属性参数必须是常量表达式、typeof表达式或属性参数类型的数组创建表达式。错误消息很清楚


本地化。城市
不是常数。我假设它只是一个静态的“只读”字段/属性。

属性参数必须在编译时固定。 请参考Jon Skeet关于SO的回答:

表达式E是一个属性参数表达式,如果 以下语句为>true:•E的类型是一个属性 参数类型(§17.1.3)。•在编译时,E的值可以是 解决以下问题之一:•恒定值。•系统。类型 反对属性参数表达式的一维数组


您能否说明您是如何声明“本地化.City”的?

以便将DisplayAttribute与您需要使用的资源一起使用

[Display(ResourceType=typeof(Localization), Name="City")]
public string City {get;set;}
不要忘记打开资源文件,并将访问修饰符设置为public而不是internal。

来源:


我同意!我只是不明白为什么框架会抛出这个错误。静态属性有什么问题?这不适用于GridView和AutoGenerateColumns。列名称显示属性名称。有线索吗?是的,我的资源是Public你是说WinForms GridView吗?据我所知,它使用的TypeDescriptor.GetProperties不尊重DisplayName属性。您可以创建自定义类型描述符并从属性中获取显示名称。@STO,我有一个类,我从参考资料中添加了显示注释,并使用GetAttributeFrom方法从中检索属性数据,但它不显示本地化的数据!
public class CustomAttribute : Attribute
{

    public CustomAttribute(Type resourceType, string resourceName)
    {
                Message = ResourceHelper.GetResourceLookup(resourceType, resourceName);
    }

    public string Message { get; set; }
}

public class ResourceHelper
{
    public static  string GetResourceLookup(Type resourceType, string resourceName)
    {
        if ((resourceType != null) && (resourceName != null))
        {
                PropertyInfo property = resourceType.GetProperty(resourceName, BindingFlags.Public | BindingFlags.Static);
                if (property == null)
                {
                        throw new InvalidOperationException(string.Format("Resource Type Does Not Have Property"));
                }
                if (property.PropertyType != typeof(string))
                {
                        throw new InvalidOperationException(string.Format("Resource Property is Not String Type"));
                }
                return (string)property.GetValue(null, null);
        }
        return null; 
        }
}