How to iterate on all properties of an object in C#?

后端 未结 3 1866
名媛妹妹
名媛妹妹 2021-02-08 16:44

I am new to C#, I want to write a function to iterate over properties of an object and set all null strings to \"\". I have heard that it is possible using something called \"Re

3条回答
  •  鱼传尺愫
    2021-02-08 16:54

    public class Foo
    {
        public string Prop1 { get; set; }
        public string Prop2 { get; set; }
        public int Prop3 { get; set; }
    }
    
    class Program
    {
        static void Main(string[] args)
        {
            var foo = new Foo();
    
            // Use reflection to get all string properties 
            // that have getters and setters
            var properties = from p in typeof(Foo).GetProperties()
                             where p.PropertyType == typeof(string) &&
                                   p.CanRead &&
                                   p.CanWrite
                             select p;
    
            foreach (var property in properties)
            {
                var value = (string)property.GetValue(foo, null);
                if (value == null)
                {
                    property.SetValue(foo, string.Empty, null);
                }
            }
    
            // at this stage foo should no longer have null string properties
        }
    }
    

提交回复
热议问题