lundi 14 août 2017

Strip all values from C# objects using Reflection

I have the following method which is used to retrieve all values as strings from an object using reflection. The object can have IEnumerables within them and I also want to retrieve these values. A list of ignore fields also needs to be taken into account so that those field's values are not returned.

public static IEnumerable<string> StringContent(this object obj, IEnumerable<string> ignoreFields = null)
{
    Type t = obj.GetType();
    foreach (var field in t.GetProperties())
    {
        if (ignoreFields != null && ignoreFields.Contains(field.Name))
        {
            continue;
        }
        var value = field.GetValue(obj);
        if (value != null)
        {
            if (value is IEnumerable<object>)
            {
                foreach (var item in (IEnumerable<object>)value)
                {
                    foreach (var subValue in item.StringContent())
                    {
                        yield return subValue.ToString();
                    }
                }
            }
            else
            {
                yield return value.ToString();
            }
        }
    }
}

This method does work perfectly and gives me the correct result. However, I need to speed it up as much as possible because this is performed a lot of times.

Does anybody have any suggestions?

Thanks in advance!





Aucun commentaire:

Enregistrer un commentaire