2012-07-03 3 views
1

Как написать код отражения, который проходит через мой проект, и ищет классы со специальным атрибутом и может собирать 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

Вот отличный ресурс (через мой Google-Fu): http://oreilly.com/catalog/progcsharp/chapter /ch18.html – JDB

ответ

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 и увидеть ожидаемые значения. (если у вас есть проблемы с этой частью, обязательно следуйте советам по вашему вопросу)

Смежные вопросы