C# Iterate through Class properties

前端 未结 4 917
猫巷女王i
猫巷女王i 2020-11-29 16:43

I\'m currently setting all of the values of my class object Record.

This is the code that I\'m using to populate the record at the moment, property by p

4条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-29 17:22

    Yes, you could make an indexer on your Record class that maps from the property name to the correct property. This would keep all the binding from property name to property in one place eg:

    public class Record
    {
        public string ItemType { get; set; }
    
        public string this[string propertyName]
        {
            set
            {
                switch (propertyName)
                {
                    case "itemType":
                        ItemType = value;
                        break;
                        // etc
                }   
            }
        }
    }
    

    Alternatively, as others have mentioned, use reflection.

提交回复
热议问题