Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for indexers (support for Arrays/Lists/Dictionaries/etc) #26

Open
crozone opened this issue Jun 23, 2021 · 1 comment
Open
Milestone

Comments

@crozone
Copy link
Owner

crozone commented Jun 23, 2021

At present, FormatWith supports basic property navigations in parameter keys. However, it does not support combining this with indexers to navigate into objects arrays, lists, or dictionaries.

For example, this is currently supported:

string result = "{foo.bar}".FormatWith(new 
{ 
    foo = new { bar = "test" }
});

However, we should be able to do this:

string result = "{foo[\"bar\"].Length}".FormatWith(new 
{
    foo = new Dictionary<string, string> { ["bar"] = "test" }
});

This is the code that will need to be changed:

private static bool TryGetPropertyFromObject(string key, object replacementObject, out object value)
{
// need to split this into accessors so we can traverse nested objects
var members = key.Split(new[] { "." }, StringSplitOptions.None);
if (members.Length == 1)
{
PropertyInfo propertyInfo = replacementObject.GetType().GetProperty(key, propertyBindingFlags);
if (propertyInfo == null)
{
value = null;
return false;
}
else
{
value = propertyInfo.GetValue(replacementObject);
return true;
}
}
else
{
object currentObject = replacementObject;
foreach (var member in members)
{
PropertyInfo propertyInfo = currentObject.GetType().GetProperty(member, propertyBindingFlags);
if (propertyInfo == null)
{
value = null;
return false;
}
else
{
currentObject = propertyInfo.GetValue(currentObject);
}
}
value = currentObject;
return true;
}
}

@crozone
Copy link
Owner Author

crozone commented Jun 23, 2021

This will potentially solve #23.

@crozone crozone added this to the 4.0 milestone Jun 23, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant