jeudi 18 novembre 2021

Using reflection to trim all strings on an object

Say I have a simple model structure like below and I want to trim the whitespace off of each string in the nested model (Request which contains a Friend)

{
    public string id { get; set; }
    public string name { get; set; }
}

public class Request
{
    public string name{ get; set; }
    public string street { get; set; }
    public List<string> tags { get; set; }
    public Friend friend { get; set; }
    public string greeting { get; set; }
    public string favoriteFruit { get; set; }
} 

This implementation only handles the strings on the top Request level - I need to be able to handle the Friend level (nested) strings as well.

private static T TrimWhiteSpaceOnRequest<T>(T obj)
    {
        if (obj != null) 
        {
            PropertyInfo[] properties = obj!.GetType().GetProperties();
            foreach (PropertyInfo property in properties) {
                try
                {
                    if (property.PropertyType == typeof(string)) 
                    {
                        var o = property.GetValue(obj, null) ?? "";
                        string s = (string)o;
                        property.SetValue(obj, s.Trim());
                    }
                    else
                    {
                        //handle nested Friend object here
                        
                    }
                }
                catch (Exception)
                {
                    log.info("Error converting field " + field.getName());
                }
            }
            
        }
        return obj;
    }

What can I put in the else to reach the nested layer?





Aucun commentaire:

Enregistrer un commentaire