C# get and set property by variable name

后端 未结 4 535
遇见更好的自我
遇见更好的自我 2021-01-01 23:46

Is there any way to do this? I try to test if a property of an object exists and if it does, I want to set a value to it. (Maybe the complete idea is bad, if true - why?)

4条回答
  •  情书的邮戳
    2021-01-02 00:11

    Yes, your looking for the PropertyInfo.SetValue method e.g.

    var propInfo = info.GetType().GetProperty(propertyName);
    if (propInfo != null)
    {
        propInfo.SetValue(info, value, null);
    }
    

提交回复
热议问题