Iterate through Object's own Strings & Trim each

后端 未结 4 1839
梦谈多话
梦谈多话 2020-12-28 20:45

I have multiple large objects which each have about 60 strings. I have to trim all those strings, and I\'d like to do so without having to go this.mystring = this.mystring.T

4条回答
  •  盖世英雄少女心
    2020-12-28 21:29

    Not necessary to make IEnumerable check in the props-loop and if actual instance is a IEnumerable, props are ignored. Fix for IEnumerable part:

    private void TrimWhitespace(object instance)
    {
        if (instance != null)
        {
            if (instance is IEnumerable)
            {
                foreach (var item in (IEnumerable)instance)
                {
                    TrimWhitespace(item);
                }
            }
    
            var props = instance.GetType()
                    .GetProperties(BindingFlags.Instance | BindingFlags.Public)
                // Ignore indexers
                    .Where(prop => prop.GetIndexParameters().Length == 0)
                // Must be both readable and writable
                    .Where(prop => prop.CanWrite && prop.CanRead);
    
            foreach (PropertyInfo prop in props)
            {
                if (prop.GetValue(instance, null) is string)
                {
                    string value = (string)prop.GetValue(instance, null);
                    if (value != null)
                    {
                        value = value.Trim();
                        prop.SetValue(instance, value, null);
                    }
                }
                else 
                    TrimWhitespace(prop.GetValue(instance, null));
            }
        }
    }
    

提交回复
热议问题