Update a property on an object knowing only its name

后端 未结 3 868
梦如初夏
梦如初夏 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:27

    I am not sure I understand you correctly but here is a try

    public static class MyExtensions
    {
        public static void SetProperty(this object obj, string propName, object value)
        {
            obj.GetType().GetProperty(propName).SetValue(obj, value, null);
        }
    }
    

    Usage like

    Form f = new Form();
    f.SetProperty("Text", "Form222");
    
    0 讨论(0)
  • 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>(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, ...);
    
    0 讨论(0)
  • 2021-01-06 04:41

    You're going to have to use reflection to accomplish that. Here's a short example:

    class Foo
    {
        public int Num { get; set; }
    }
    
    static void Main(string[] args)
    {
        Foo foo = new Foo() { Num = 7 };
    
        Console.WriteLine(typeof(Foo).GetProperty("Num").GetValue(foo, null));
    }
    
    0 讨论(0)
提交回复
热议问题