记一次C#使用反射
一般来说程序员用到反射的地方并不多,如果你想从一个对象 动态获得他的方法 就用反射。
这次我需要给一个静态模型初始化赋值需要用到反射。
首先我先去微软官方网站搜索了一下反射,发现下面几大关键点。
MemberInfo、MethodInfo、FieldInfo 和 PropertyInfo
MemberInfo 获取有关成员属性的信息并提供对成员元数据的访问权限。
MethodInfo 发现方法的属性并提供对方法元数据的访问。
FieldInfo 发现字段的属性并提供对字段元数据的访问权限。
PropertyInfo 发现属性 (Property) 的属性 (Attribute) 并提供对属性 (Property) 元数据的访问。
我的这个静态模型里面有静态字段和静态模型(但是此模型的字段是公开的)。要为这个静态模型赋值我选择了FieldInfo类(为静态字段赋值)和PropertyInfo类(为公开字段赋值)。
再附上此次的核心代码:
public object Create(object parent, object configContext, System.Xml.XmlNode section)
{
Type t = typeof(TLConfig);
foreach (FieldInfo item in t.GetFields())
{
if(section.SelectNodes(item.Name)[0] != null)
{
item.SetValue(this, section.SelectNodes(item.Name)[0].SelectSingleNode("@value").InnerText);
}
}
foreach (PropertyInfo pi in t.GetProperties())
{
foreach (PropertyInfo item in pi.PropertyType.GetProperties())
{
var propertySection = section.SelectNodes(pi.Name)[0];
if (propertySection != null)
{
if (propertySection.SelectNodes(item.Name)[0] != null) {
item.SetValue(pi.GetValue(this), propertySection.SelectNodes(item.Name)[0].SelectSingleNode("@value").InnerText);
}
}
}
}
return null;
}

浙公网安备 33010602011771号