Created
June 15, 2023 03:03
-
-
Save FriendSea/a39bd20a474b19f36d0f1f74c0dbe8bc to your computer and use it in GitHub Desktop.
木構造にルートや親の参照を注入する。デシリアライズしたオブジェクトとかに使う
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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