Skip to content

Instantly share code, notes, and snippets.

@FriendSea
Created June 15, 2023 03:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save FriendSea/a39bd20a474b19f36d0f1f74c0dbe8bc to your computer and use it in GitHub Desktop.
Save FriendSea/a39bd20a474b19f36d0f1f74c0dbe8bc to your computer and use it in GitHub Desktop.
木構造にルートや親の参照を注入する。デシリアライズしたオブジェクトとかに使う
using System.Reflection;
public class InjectRootAttribute : Attribute{}
public class InjectParentAttribute : Attribute{}
public static class TreeReferenceInjector {
public static T InjectRoot<T>(this T target, object root = null){
foreach(var info in target.GetType().GetFields(BindingFlags.Public | BindingFlags.Instance)){
if(info.FieldType.IsArray){
var array = info.GetValue(target) as object[];
if(array == null) continue;
foreach(var obj in array)
InjectRoot(obj, root ?? target);
}else{
if(info.CustomAttributes.Any(att => att.AttributeType == typeof(InjectRootAttribute)))
info.SetValue(target, root);
if(info.CustomAttributes.Any(att => att.AttributeType == typeof(InjectRootAttribute) || att.AttributeType == typeof(InjectParentAttribute)))
continue;
var obj = info.GetValue(target);
if(obj == null) continue;
InjectRoot(obj, root ?? target);
}
}
return target;
}
public static T InjectParent<T>(this T target, object parent = null){
foreach(var info in target.GetType().GetFields(BindingFlags.Public | BindingFlags.Instance)){
if(info.FieldType.IsArray){
var array = info.GetValue(target) as object[];
if(array == null) continue;
foreach(var obj in array)
InjectParent(obj, target);
}else{
if(info.CustomAttributes.Any(att => att.AttributeType == typeof(InjectParentAttribute)))
info.SetValue(target, parent);
if(info.CustomAttributes.Any(att => att.AttributeType == typeof(InjectRootAttribute) || att.AttributeType == typeof(InjectParentAttribute)))
continue;
var obj = info.GetValue(target);
if(obj == null) continue;
InjectParent(obj, target);
}
}
return target;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment