Skip to content

Commit

Permalink
feat: support nullable properties
Browse files Browse the repository at this point in the history
  • Loading branch information
rdavisau committed Apr 23, 2019
1 parent d3e6e57 commit 9beb6ee
Showing 1 changed file with 17 additions and 8 deletions.
25 changes: 17 additions & 8 deletions src/DumpEditable/EditorRule.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,14 +41,17 @@ public static EditorRule ForType<T>(Func<object, PropertyInfo, Action, object> g
.Concat(new [] { "]" }))
);

public static EditorRule ForTypeWithStringBasedEditor<T>(ParseFunc<string, T, bool> parseFunc)
public static EditorRule ForTypeWithStringBasedEditor<T>(ParseFunc<string, T, bool> parseFunc, bool supportNullable = true)
=> new EditorRule
{
Match = (o, info) => info.PropertyType == typeof(T),
Editor = (o, info, changed) => GetStringInputBasedEditor(o, info, changed, parseFunc)
Match = (o, info) =>
info.PropertyType == typeof(T)
|| (supportNullable && Nullable.GetUnderlyingType(info.PropertyType) == typeof(T)),
Editor = (o, info, changed) => GetStringInputBasedEditor(o, info, changed, parseFunc, supportNullable)
};

protected static object GetStringInputBasedEditor<TOut>(object o, PropertyInfo p, Action changeCallback, EditorRule.ParseFunc<string, TOut, bool> parseFunc)
protected static object GetStringInputBasedEditor<TOut>(object o, PropertyInfo p, Action changeCallback, EditorRule.ParseFunc<string, TOut, bool> parseFunc,
bool supportNullable = true)
{
var currVal = p.GetValue(o);
var desc = currVal != null ? $"{currVal}" : "null";
Expand All @@ -58,10 +61,16 @@ protected static object GetStringInputBasedEditor<TOut>(object o, PropertyInfo p
var newVal = Interaction.InputBox("Set value for " + p.Name, p.Name, $"{currVal}");
var canConvert = parseFunc(newVal, out var output);
if (!canConvert)
return;
p.SetValue(o, output);
if (canConvert)
{
p.SetValue(o, output);
}
else if (supportNullable && (newVal == String.Empty))
{
p.SetValue(o, null);
}
else
return; // can't convert
changeCallback?.Invoke();
Expand Down

0 comments on commit 9beb6ee

Please sign in to comment.