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

前端 未结 7 775
借酒劲吻你
借酒劲吻你 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:49

    If you don't specify any binding flags you will get the public, instance properties -- which is what you want. But then you will need to check if the PropertyType on the PropertyInfo object is of type String. Unless you know in advance, you'll also need to check whether the property is readable/writable as @Fredrik indicates.

    using System.Linq;
    
    public static void ReplaceEmptyStrings(List list, string replacement)
    {
        var properties = typeof(T).GetProperties()
                                  .Where( p => p.PropertyType == typeof(string) );
        foreach(var p in properties)
        {
            foreach(var item in list)
            {
                if(string.IsNullOrEmpty((string) p.GetValue(item, null)))
                    p.SetValue(item, replacement, null);
            }
        }
    }
    

提交回复
热议问题