Expressionで辞書に登録されていればそれを返すし、登録されていなければデフォルト値を登録したうえでそれを返すコード
Expression完全に理解した
private static readonly ParameterExpression dicParameterExpression = Expression.Parameter(typeof(Dictionary<string, object>), "dic"); private static readonly MethodInfo containsKeyMethod = typeof(Dictionary<string, object>).GetMethod("ContainsKey"); private static readonly MethodInfo addMethod = typeof(Dictionary<string, object>).GetMethod("Add"); private static readonly MethodInfo debugLogErrorMethod = typeof(Debug).GetMethod("LogError", new[] {typeof(object)}); //(下記と同等のコード) // T value; // value = default(T); // if (dic.ContainsKey(key)) // value = dic[key]; // else // dic.Add(key, value); // return value; var keyExpression = Expression.Constant(statementString); var valueExpression = Expression.Parameter(typeof(T), $"{statementString}_value"); var getValueExpression = Expression.Convert(Expression.Property(dicParameterExpression, "Item", keyExpression), typeof(T)); expression = Expression.Block( typeof(T), new[] { valueExpression }, Expression.Assign(valueExpression, Expression.Default(typeof(T))), Expression.IfThenElse( Expression.Call(dicParameterExpression, containsKeyMethod, keyExpression), Expression.Assign(valueExpression, getValueExpression), Expression.Block( Expression.Call(dicParameterExpression, addMethod, keyExpression, Expression.Convert(valueExpression, typeof(object))), Expression.Call(debugLogErrorMethod, Expression.Constant($"{statementString}が登録されていなかったためデフォルト値を登録して使用します"))) ), valueExpression );