mirror of
https://github.com/proxysu/ProxySU.git
synced 2024-11-25 06:36:08 +03:00
63 lines
2.0 KiB
C#
63 lines
2.0 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.IO;
|
|
using System.Linq;
|
|
using System.Reflection;
|
|
using System.Runtime.Serialization.Formatters.Binary;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace System
|
|
{
|
|
public static class Extensions
|
|
{
|
|
// Deep clone
|
|
public static T DeepClone<T>(this T obj)
|
|
{
|
|
if (obj == null)
|
|
throw new ArgumentNullException("Object cannot be null");
|
|
return (T)Process(obj);
|
|
}
|
|
|
|
static object Process(object obj)
|
|
{
|
|
if (obj == null)
|
|
return null;
|
|
Type type = obj.GetType();
|
|
if (type.IsValueType || type == typeof(string))
|
|
{
|
|
return obj;
|
|
}
|
|
else if (type.IsArray)
|
|
{
|
|
Type elementType = Type.GetType(
|
|
type.FullName.Replace("[]", string.Empty));
|
|
var array = obj as Array;
|
|
Array copied = Array.CreateInstance(elementType, array.Length);
|
|
for (int i = 0; i < array.Length; i++)
|
|
{
|
|
copied.SetValue(Process(array.GetValue(i)), i);
|
|
}
|
|
return Convert.ChangeType(copied, obj.GetType());
|
|
}
|
|
else if (type.IsClass)
|
|
{
|
|
object toret = Activator.CreateInstance(obj.GetType());
|
|
FieldInfo[] fields = type.GetFields(BindingFlags.Public |
|
|
BindingFlags.NonPublic | BindingFlags.Instance);
|
|
foreach (FieldInfo field in fields)
|
|
{
|
|
object fieldValue = field.GetValue(obj);
|
|
if (fieldValue == null)
|
|
continue;
|
|
field.SetValue(toret, Process(fieldValue));
|
|
}
|
|
return toret;
|
|
}
|
|
else
|
|
throw new ArgumentException("Unknown type");
|
|
}
|
|
|
|
}
|
|
}
|