2012-12-23 143 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。 –