2020-06-17 15:55:58 +02:00
|
|
|
using Newtonsoft.Json;
|
|
|
|
|
using System;
|
2021-08-25 15:20:44 +02:00
|
|
|
using System.Collections.Generic;
|
|
|
|
|
using zero.Core.Attributes;
|
2020-09-18 01:06:21 +02:00
|
|
|
using zero.Core.Utils;
|
2020-05-09 20:34:10 +02:00
|
|
|
|
|
|
|
|
namespace zero.Core.Extensions
|
|
|
|
|
{
|
|
|
|
|
public static class ObjectExtensions
|
|
|
|
|
{
|
|
|
|
|
public static bool Is<T>(this Type type)
|
|
|
|
|
{
|
|
|
|
|
return type.IsAssignableFrom(typeof(T));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
public static bool Is<T>(this object obj)
|
|
|
|
|
{
|
|
|
|
|
return obj.GetType().IsAssignableFrom(typeof(T));
|
|
|
|
|
}
|
2020-06-17 15:55:58 +02:00
|
|
|
|
|
|
|
|
|
|
|
|
|
public static T Clone<T>(this T obj)
|
|
|
|
|
{
|
2020-08-27 11:41:40 +02:00
|
|
|
Type type = obj.GetType();
|
2020-11-24 12:02:03 +01:00
|
|
|
return (T)JsonConvert.DeserializeObject(JsonConvert.SerializeObject(obj, new RefJsonConverter()), type, new RefJsonConverter());
|
2020-06-17 15:55:58 +02:00
|
|
|
}
|
2020-11-09 16:09:22 +01:00
|
|
|
|
|
|
|
|
public static T CloneLax<T>(this object obj)
|
|
|
|
|
{
|
2020-11-24 12:02:03 +01:00
|
|
|
return JsonConvert.DeserializeObject<T>(JsonConvert.SerializeObject(obj, new RefJsonConverter()), new RefJsonConverter());
|
2020-11-09 16:09:22 +01:00
|
|
|
}
|
2021-08-25 15:20:44 +02:00
|
|
|
|
|
|
|
|
public static T AutoSetIds<T>(this T obj)
|
|
|
|
|
{
|
|
|
|
|
// find all Raven Ids
|
|
|
|
|
List<ObjectTraverser.Result<GenerateIdAttribute>> ravenIds = ObjectTraverser.FindAttribute<GenerateIdAttribute>(obj);
|
|
|
|
|
|
|
|
|
|
// set unset Raven Ids
|
|
|
|
|
foreach (ObjectTraverser.Result<GenerateIdAttribute> item in ravenIds)
|
|
|
|
|
{
|
|
|
|
|
string id = item.Property.GetValue(item.Parent, null) as string;
|
|
|
|
|
if (String.IsNullOrWhiteSpace(id))
|
|
|
|
|
{
|
|
|
|
|
item.Property.SetValue(item.Parent, item.Item.Length.HasValue ? IdGenerator.Create(item.Item.Length.Value) : IdGenerator.Create());
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return obj;
|
|
|
|
|
}
|
2020-05-09 20:34:10 +02:00
|
|
|
}
|
|
|
|
|
}
|