Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update a property on an object knowing only its name

Tags:

c#

I have some public variables that are defined as follows:

public class FieldsToMonitor
{
    public int Id { get; set; }
    public string Title { get; set; }
    public int Rev {get; set;}
}

I now want to populate those variable with values, but the fm.[varible name] needs be same as field.Name. Here how I would populate in loop if I knew the property name ahead of time and the order of the property name:

// loop 1
fm.Id = revision.Fields[field.Name].Value;

// ... loop 2 ...
fm.Title = revision.Fields[field.Name].Value;

// ... loop 3 ...
fm.Rev = revision.Fields[field.Name].Value;

Here is what I would like to do where field.Name can be substituted with property name:

  • fm.ID becomes fm.[field.Name] where field.Name == "ID"

  • fm.Title becomes fm.[field.Name] where field.Name == "Title"

  • fm.Rev becomes fm.[field.Name] and where field.Name == "Rev"

Is there a solution for this?

Here is more code of what I have so far:

public class FieldsToMonitor
{
    public int Id { get; set; }
    public string Title { get; set; }
    public int Rev {get; set;}
}

static BindingList<FieldsToMonitor> FieldsToMonitorList
     = new BindingList<FieldsToMonitor>();
// ...

// Loop through the work item revisions
foreach (Revision revision in wi.Revisions)
{
    fm = new FieldsToMonitor();
    // Get values for the work item fields for each revision
    var row = dataTable.NewRow();
    foreach (Field field in wi.Fields)
    {
        fieldNameType = field.Name;
        switch (fieldNameType)
        {
            case "ID":
            case "Title":
            case "Rev":
                // the following doesn't work
                fm + ".[field.Name]" = revision.Fields[field.Name].Value; 
                fm[field.Name] = revision.Fields[field.Name].Value;
                row[field.Name] = revision.Fields[field.Name].Value;
                break;
        }
    }
}
like image 977
Nick Avatar asked Mar 15 '12 15:03

Nick


1 Answers

This is all heavily dependent on how these values are being retrieved, and it is difficult to tell from your limited example if the values are strings or the correct type just boxed as an object.

That being said, the following could work (but is hardly efficient):

public static void SetValue<T>(T obj, string propertyName, object value)
{
    // these should be cached if possible
    Type type = typeof(T);
    PropertyInfo pi = type.GetProperty(propertyName);

    pi.SetValue(obj, Convert.ChangeType(value, pi.PropertyType), null);
}

Used like:

SetValue(fm, field.Name, revision.Fields[field.Name].Value);
// or SetValue<FieldsToMonitor>(fm, ...);
like image 154
user7116 Avatar answered Oct 21 '22 15:10

user7116