Reputation: 11062
Localizing properties of the class are out of box by using the DisplayAttribute
.
When trying to localize Attributes using a resource file EmployeeResx.resx , EmployeeResx.fr.res....,
static class EmployeeResx.Designer.cs
is generated with static string properties like:
public static string LastName {
get {
return ResourceManager.GetString("LastName", resourceCulture);
}
}
Trying to use the static string to localize the properties of the Attributes (Option in this example), like:
[Option('l', "lastname", HelpText = EmployeeResx.LastName)]
public string LastName { get; set; }
c# compiler raise error:
Error CS0182 An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
There are many attributes need to be localized.
How to localize the string properties of the Attributes like the above example?
Upvotes: 1
Views: 1069
Reputation: 3769
Make a derived attribute type. Pass the resource name into the derived attribute class. The derived attribute class can retrieve the resource string and pass it into the constructor of the base class.
If your Option attribute has a single string parameter, the derived class would be something like this.
internal class localized_OptionAttribute : OptionAttribute
{
public localized_Option ( string ResourceName )
: base ( <root namespace>.Properties.Resources.ResourceManager.GetString ( ResourceName ) )
{
}
}
Then you can use the new attribute in place of the original one:
[localized_Option("LastName")]
public string LastName { get; set; }
where "LastName" is now used as the resource name.
It looks like your attribute has some additional parameters, which you would have to define as additional parameters to the constructor of the derived class. I have left them out for simplicity.
Upvotes: 2