C# c语言中属性字符串属性的本地化#

C# c语言中属性字符串属性的本地化#,c#,localization,attributes,resx,C#,Localization,Attributes,Resx,通过使用DisplayAttribute,可以现成地本地化类的属性 当尝试使用资源文件EmployeeResx.resx、EmployeeResx.fr.res..本地化属性时,静态类EmployeeResx.Designer.cs会生成静态字符串属性,如: public static string LastName { get { return ResourceManager.GetString("LastName", resourceCulture); } }

通过使用
DisplayAttribute
,可以现成地本地化类的属性

当尝试使用资源文件
EmployeeResx.resx、EmployeeResx.fr.res..本地化属性时,
静态类
EmployeeResx.Designer.cs
会生成静态字符串属性,如:

public static string LastName {
    get {
        return ResourceManager.GetString("LastName", resourceCulture);
    }
} 
尝试使用静态字符串本地化属性的属性(本例中的选项),如:

c#编译器引发错误:

错误CS0182属性参数必须是常量表达式、typeof表达式或属性参数类型的数组创建表达式

有许多属性需要本地化


如何像上面的例子一样本地化属性的字符串属性?

创建一个派生属性类型。将资源名称传递到派生属性类中。派生属性类可以检索资源字符串并将其传递给基类的构造函数

如果Option属性只有一个字符串参数,那么派生类将如下所示

internal class localized_OptionAttribute : OptionAttribute
{
  public localized_Option ( string ResourceName )
    : base ( <root namespace>.Properties.Resources.ResourceManager.GetString ( ResourceName ) )
  {
  }
}
其中“LastName”现在用作资源名称

属性似乎有一些附加参数,您必须将这些参数定义为派生类构造函数的附加参数。为了简单起见,我省略了它们

internal class localized_OptionAttribute : OptionAttribute
{
  public localized_Option ( string ResourceName )
    : base ( <root namespace>.Properties.Resources.ResourceManager.GetString ( ResourceName ) )
  {
  }
}
[localized_Option("LastName")]
public string  LastName { get; set; }