Update a property on an object knowing only its name

后端 未结 3 904
梦如初夏
梦如初夏 2021-01-06 03:40

I have some public variables that are defined as follows:

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


        
3条回答
  •  忘掉有多难
    2021-01-06 04:36

    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 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(fm, ...);
    

提交回复
热议问题