您的位置:首页 > 其它

反射常用功能-持续更新

2011-02-12 18:09 375 查看
反射判断 某个对象 是否 是泛型集合的类型
public bool isCollection(object o)

{

return typeof(ICollection).IsAssignableFrom(o.GetType())

|| typeof(ICollection<>).IsAssignableFrom(o.GetType());

}

获取类实例

public static object Load(string assembly, string className)
{
return Assembly.Load(assembly).CreateInstance(className);
}

获取指定属性

代码 Type dataType = Type.GetType(ClassName);
MethodInfo parseMethod = dataType.GetMethod("Parse", BindingFlags.Public | BindingFlags.IgnoreCase
| BindingFlags.Static | BindingFlags.FlattenHierarchy, null, new Type[] { typeof(string) }, null); 反射获取某个属性集合(如获取DataTable的columns属性,并且遍历它)

DataTable dtSource = (DataTable)data;
Type type = dtSource.GetType();
PropertyInfo pi = type.GetProperty("Columns");
IEnumerable listObject = (IEnumerable)pi.GetValue(dtSource, null); 反射设置属性

public static void SetPropertyValue(this PropertyInfo property, object target, object value)
{
if (null != property && property.CanWrite)
{
if (value.GetType() == typeof(string))
{
// 对换行符进行转换
value = value.ToString().Replace("\\r", "\r").
Replace("\\n", "\n").Replace("<br>", "\n");
}
value = GetObjectInstance(property.PropertyType, value.ToString());
property.SetValue(target, value, null);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: