鉴于字典喜欢收集有以下类:创建使用常量字符串字段可能的字符串值重复
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";
}
注意Z
常数,它有不同的CustomAttribute
参数的重复。
我想,使用反射,迭代的类和生产类字典收集与以下属性:
dict.CustomGet(A.Z) == 3
dict.CustomGet(B.Z) == 6
现在,我知道,我可以很容易做到:
dict.CustomGet(()=>A.Z)
实现为:
public int CustomGet(Expression<Func<string>> expr){...}
,并使用Expression对象来找出我正在访问哪个课程和字段,并且有内部集合,如Dictionary<Type,Dictionary<string,int>>
或甚至可能是Dictionary<FieldInfo,int>
,但它要求我每次写出可疑的()=>Class.ConstantName
。
请注意,我无法将字符串文字值更改为唯一。
以上就是我目前的问题,我觉得我的问题是:我可以用另一种方式表达比告诉C#中的唯一对象传递给CustomGet
代替非唯一字符串?
附注:我想比较通过的字符串的引用,但由于实习,我认为很有可能"z"
将ReferenceEqual
另一个"z"
。
最后一点:这主要是为了好玩,我可以(并且很可能会)完全避免这个问题,但我想知道C#的限制是供将来参考:)