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

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

    I agree with other answers, but I prefer to refactor the search itself to be easly queried with Linq, so the query could be as follow:

            var asm = Assembly.GetExecutingAssembly();
            var properties = (from prop
                                  in asm.GetType()
                                    .GetProperties(BindingFlags.Public | BindingFlags.Instance)
                              where 
                                prop.PropertyType == typeof (string) && 
                                prop.CanWrite && 
                                prop.CanRead
                              select prop).ToList();
            properties.ForEach(p => Debug.WriteLine(p.Name));
    

    I took for my example the Assembly type, which hasn't read/write string properties, but if the same code search for just read properties, the result will be:

    • CodeBase
    • EscapedCodeBase
    • FullName
    • Location
    • ImageRuntimeVersion

    Which are the string read-only Assembly type properties

提交回复
热议问题