1

如何使用反射访问 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;
        ...
     }
  }
4

1 回答 1

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]));
于 2012-12-23T00:33:37.800 回答