如何编写遍历我的项目的反射代码,并查找具有特殊属性的类,并能够收集2条信息:ClassName.PropertyName和传递到属性内的ResourceManager.GetValue的字符串。我的代码如下。请帮忙。感谢
[TestMethod]
public void TestMethod1()
{
Dictionary<string, string> mydictionary = new Dictionary<string, string>();
mydictionary = ParseAllClassesWithAttribute("MyAttribute");
Assert.AreEqual(mydictionary["MyClass.FirstNameIsRequired"].ToString(), "First Name is Required");
}
private Dictionary<string, string> ParseAllClassesWithAttribute(string p)
{
Dictionary<string,string> dictionary = new Dictionary<string, string>();
// use reflection to go through the class that is decorated by attribute MyAttribute
// and is able to extract ClassName.PropertyName along with what is Inside
// GetValue method parameter.
// In the following I am artificially populating the dictionary object.
dictionary.Add("MyClass.FirstNameIsRequired", "First Name is Required");
return dictionary;
}
[MyAttribute]
public class MyClass
{
public string FirstNameIsRequired
{
get
{
return ResourceManager.GetValue("First Name is required");
}
}
}
public static class ResourceManager
{
public static string GetValue(string key)
{
return String.Format("some value from the database based on key {0}",key);
}
}
答案 0 :(得分:1)
反射无法提取"First Name is Required"
值,除非您获取IL字节并解析它们。这是一个潜在的解决方案:
[AttributeUsage(AttributeTargets.Property)]
public class MyAttribute : Attribute
{
public string TheString { get; private set; }
public MyAttribute(string theString)
{
this.TheString = theString;
}
}
const string FirstNameIsRequiredThing = "First Name is required";
[MyAttribute(FirstNameIsRequiredThing)]
public string FirstNameIsRequired
{
get
{
return ResourceManager.GetValue(FirstNameIsRequiredThing);
}
}
现在,您可以使用MyAttribute
阅读所有属性并查看预期值。 (如果您在使用此部分时遇到问题,请务必遵循您对问题的评论意见)