如何使用反射访问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 :(得分: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]));