通过反射访问属性
本文关键字:属性 访问 反射 | 更新日期: 2023-09-27 17:49:13
如何使用反射访问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;
...
}
}
下面是通过反射获取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。如果您想获得一个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]));