关于c#:反射

35次阅读

共计 414 个字符,预计需要花费 2 分钟才能阅读完成。

    public static T DeepCopyByReflect<T>(T obj)
    {
        // 如果是字符串或值类型则间接返回
        if (obj is string || obj.GetType().IsValueType) return obj;

        object retval = Activator.CreateInstance(obj.GetType());
        FieldInfo[] fields = obj.GetType().GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);
        foreach (FieldInfo field in fields)
        {try { field.SetValue(retval, DeepCopyByReflect(field.GetValue(obj))); }
            catch {}}
        return (T)retval;
    }

正文完
 0