根据属性名称更改对象属性的值

时间:2021-06-11 02:38:42

标签: c# reflection properties variable-assignment variable-names

我想根据属性的名称更改对象中目标属性的值。 示例:

// Returns a list of all the properties of an object
PropertyInfo[] properties = GetProperties(myObject);

// Set the values of all properties that contain "Show_" in their name to -1
foreach (PropertyInfo property in properties)
{
    if (property.Name.Contains("Show_"))
    {
        // update myObject's property value to -1
        // i.e. something like:
        // myObject.(property.Name) = -1;
    }
}

我该怎么做?

谢谢

1 个答案:

答案 0 :(得分:1)

您可以使用SetValue

property.SetValue(myObject, -1, null);

您可以阅读文档here.