C#: How to get all public (both get and set) string properties of a type

前端 未结 7 711
借酒劲吻你
借酒劲吻你 2020-12-02 14:21

I am trying to make a method that will go through a list of generic objects and replace all their properties of type string which is either null or

相关标签:
7条回答
  • 2020-12-02 14:52

    Your code rewritten. Does not use LINQ nor var.

    public static void ReplaceEmptyStrings<T>(List<T> list, string replacement)
    {
        PropertyInfo[] properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
    
        foreach (PropertyInfo p in properties)
        {
            // Only work with strings
            if (p.PropertyType != typeof(string)) { continue; }
    
            // If not writable then cannot null it; if not readable then cannot check it's value
            if (!p.CanWrite || !p.CanRead) { continue; }
    
            MethodInfo mget = p.GetGetMethod(false);
            MethodInfo mset = p.GetSetMethod(false);
    
            // Get and set methods have to be public
            if (mget == null) { continue; }
            if (mset == null) { continue; }
    
            foreach (T item in list)
            {
                if (string.IsNullOrEmpty((string)p.GetValue(item, null)))
                {
                    p.SetValue(item, replacement, null);
                }
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题