C# Iterate through Class properties

前端 未结 4 906
猫巷女王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.

    0 讨论(0)
  • 2020-11-29 17:31

    I tried what Samuel Slade has suggested. Didn't work for me. The PropertyInfo list was coming as empty. So, I tried the following and it worked for me.

        Type type = typeof(Record);
        FieldInfo[] properties = type.GetFields();
        foreach (FieldInfo property in properties) {
           Debug.LogError(property.Name);
        }
    
    0 讨论(0)
  • 2020-11-29 17:40

    You could possibly use Reflection to do this. As far as I understand it, you could enumerate the properties of your class and set the values. You would have to try this out and make sure you understand the order of the properties though. Refer to this MSDN Documentation for more information on this approach.

    For a hint, you could possibly do something like:

    Record record = new Record();
    
    PropertyInfo[] properties = typeof(Record).GetProperties();
    foreach (PropertyInfo property in properties)
    {
        property.SetValue(record, value);
    }
    

    Where value is the value you're wanting to write in (so from your resultItems array).

    0 讨论(0)
  • 2020-11-29 17:43
    // the index of each item in fieldNames must correspond to 
    // the correct index in resultItems
    var fieldnames = new []{"itemtype", "etc etc "};
    
    for (int e = 0; e < fieldNames.Length - 1; e++)
    {
        newRecord
           .GetType()
           .GetProperty(fieldNames[e])
           .SetValue(newRecord, resultItems[e]);
    }
    
    0 讨论(0)
提交回复
热议问题