【问题标题】:Change the values of an object's properties, depending on the property's name根据属性名称更改对象属性的值
【发布时间】:2023-03-08 06:11:01
【问题描述】:

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

// 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;
    }
}

我该怎么做呢?

谢谢

【问题讨论】:

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


【解决方案1】:

你可以使用SetValue:

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

您可以阅读文档here.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-09
    • 1970-01-01
    • 2019-05-09
    • 1970-01-01
    • 1970-01-01
    • 2013-04-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多