2012-07-03 40 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讀取所有屬性,看到了預期值。 (如果你有這個部分的問題,一定要按照你的問題的意見的建議)