2012-12-23 139 views
1

如何使用反射訪問CssStyleCollection類屬性(最重要的是我感興趣的是它的鍵值集合)?CssStyleCollection類:通過反射訪問屬性

// this code runns inside class that inherited from WebControl 
PropertyInfo[] properties = GetType().GetProperties(); 

//I'am not able to do something like this 
    foreach (PropertyInfo property in properties) 
    { 
    if(property.Name == "Style") 
    { 
     IEnumerable x = property.GetValue(this, null) as IEnumerable; 
     ... 
    } 
    } 
+0

當您運行foreach循環它曾經發現「風格」,確保它不是「風格」 – MethodMan

回答

3

下面是通過反射得到Style屬性的語法:

PropertyInfo property = GetType().GetProperty("Style"); 
CssStyleCollection styles = property.GetValue(this, null) as CssStyleCollection; 
foreach (string key in styles.Keys) 
{ 
    styles[key] = ? 
} 

注意CssStyleCollection不實現IEnumerable(它實現了索引運算符),所以你不能把它轉換到。如果你想獲得一個IEnumerable,你可以提取使用styles.Keys值的鍵,並且:

IEnumerable<string> keys = styles.Keys.OfType<string>(); 
IEnumerable<KeyValuePair<string,string>> kvps 
    = keys.Select(key => new KeyValuePair<string,string>(key, styles[key])); 
+3

是,它的工作。我的錯誤是,我試圖做直接投(CssStyleCollection)...或當它沒有Imlemented此接口對待作爲Ienumerable。 –