I create a new Class Library.
Add a new resx file called MyCountry.resx and add some resources to it.
Two entries of Name and Value. I set the Access Modifier to Public so i can reference this class and use it in other projects.
I create another new Class Library and reference the above CL and all seems to work well when i write the below code:
var someValue = ClassLibrary.MyCountry.GetName;
I then decide to change an Attribute of the same class declaration to use the same Resource entry. Example of working Attribute (shortened for clarity)
[Tree("SomethingHere", "SomethingThere")]
This works but when i change it to
[Tree(ClassLibrary.MyCountry.GetName, "SomethingThere")]
I receive the error
An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type.
So change it to
[Tree(typeof(ClassLibrary.MyCountry.GetName), "SomethingThere")]
but then i receive
The type name 'GetName' does not exist in the type 'MyCountry'
When i know it does as it works on the code shown above.
Is it possible to have Attributes to use a value from a resx CL in the manner i have shown, am i missing something or is it not possible?
CodePudding user response:
As the compiler states in warning. It needs a value that is known at compile time, but the values for .resx
files are loaded at Runtime.
You can look this up in the MyCountry.Designer.cs
that is created automatically along the MyCountry.resx
file.
There are 2 Solutions for your Problem that come to my mind:
- You create a
class
that contains all all the constants.
public class MyCountry
{
public const string GetName = "Lorem Ipsum";
}
- You create/use an Source Generator that creats such a class from the
.resx
so that the compiler can access it at compile-time.