Given are following classes:
class A
{
[CustomAttribute(1)]
public const string X = "x";
[CustomAttribute(2)]
public const string Y = "y";
[CustomAttribute(3)]
public const string Z = "z";
}
class B
{
[CustomAttribute(4)]
public const string P = "p";
[CustomAttribute(5)]
public const string Q = "q";
[CustomAttribute(6)]
public const string Z = "z";
}
Note duplication of Z
constant, which has different CustomAttribute
parameter.
I would like to, using reflection, iterate both classes and produce a dictionary-like collection with following properties:
dict.CustomGet(A.Z) == 3
dict.CustomGet(B.Z) == 6
Now, I'm aware that I could fairly easily do:
dict.CustomGet(()=>A.Z)
implemented as:
public int CustomGet(Expression<Func<string>> expr){...}
and use Expression object to find out which class and field I'm accessing, and have internal collection like Dictionary<Type,Dictionary<string,int>>
or maybe even Dictionary<FieldInfo,int>
, but it requires me to write that questionable ()=>Class.ConstantName
each time.
Note, that I cannot change the string literal values to be unique.
Above is my current problem, and I think my question is: can I in another way than Expression tell C# to pass an unique object to CustomGet
instead of non-unique string?
Side note: I thought of comparing references of the passed strings, but due to interning I think it is quite likely that "z"
will ReferenceEqual
another "z"
.
Final note: This is mostly for fun, I can (and likely will) avoid the problem altogether, but I like to know what C# limitations are for future reference :)