Update a property on an object knowing only its name

后端 未结 3 869
梦如初夏
梦如初夏 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");
    

提交回复
热议问题