反射浅析

一.运行期获取类型实例的方法

1 System.Object.GetType  

用于在运行时通过查询对象查询对象元数据来获取对象的运行时类型。因为子类不能复写GetType,保证了类型安全。

通过反射机制,获取类型的元数据信息。

2 System.Type.GetType

特点:

是非强类型方法。

支持跨程序集反射,以解决模块依赖或循环引用的问题。

Type tp = Type.GetType(“System.Collection.List”);

3 typeof运算符

特点:支持强类型。

Type tp = typeof(System.Collection.List);

4.System.Reflection.Assembly的非静态方法GetType或GetTypes.

Assembly ass = Assembly.LoadFrom(@"c:\framework.dll");
Type tp = ass.GetType("Framework.SqlAccess.SqlUtils");

5.System.Reflection.Module的非静态方法GetType或GetTypes.

二.反射的应用

1.通过反射实现实体类的deep copy

private void DeepCopy<T>(T source, T des)
{
    Type typeSource = source.GetType();
    Type typeDes = des.GetType();
    PropertyInfo[] itemsSource = typeSource.GetProperties();
    PropertyInfo[] itemDes = typeDes.GetProperties();
    for (int i = 0; i < itemsSource.Length; i++)
    {
        object obj = itemsSource[i].GetValue(source, null);
        // 只读的场合des=初始值
        if (!(itemsSource[i].GetSetMethod() == null || itemsSource[i].GetSetMethod().IsPrivate))
            itemDes[i].SetValue(des, obj, null);
    }
}

未完待续。。。。

原文地址:https://www.cnblogs.com/yuanhuaming/p/1635716.html