【问题标题】:Dynamically changing other class properties with a loop使用循环动态更改其他类属性
【发布时间】:2019-06-19 23:28:13
【问题描述】:

假设strArr 是一个字符串数组。在一个循环中,我将它们中的每一个分开,因此我可以获得 keyvalue。我要做的就是在XClass 中找到一个与key 相等的属性并将其设置为value

如果 strArr 元素不包含正确的 key(如示例中的“propertyThree”),则不应更改 XClass 中的属性(因此它变为 null)。

示例代码:

string[] strArr = new string[] {
    "propertyOne:valueOne",
    "propertyTwo:valueTwo"
}

class XClass {
    public string propertyOne {get; set;}
    public string propertyTwo {get; set;}
    public string propertyThree {get; set;}
}

-----
XClass instance = new XClass();

for (int i = 0; i < strArr.Length; i++) {
    string[] arr = strArr.Split(':');
    string key = arr[0];
    string value = arr[1];

    instance.key = value;
}

// Later on...

ExampleMethod(instance); // instance's properties

这会导致错误,因为XClass 没有名为key 的属性。这很明显,但我不知道如何解决。

【问题讨论】:

  • 这里的关键词是“反射”。有很多教程/指南可以教授反射的基础知识。 StackOverflow 上还应该有问题+答案,演示如何使用给定的属性名称字符串通过反射设置属性。
  • 我认为string[] arr = strArr.Split(':'); 不会编译...strArr 是一个数组,而不是string

标签: c# loops class properties


【解决方案1】:

您可以使用instance 类型的GetProperty 方法查找名称与字符串匹配的属性,然后对该属性调用SetValue 来设置实例上的值。

如果没有找到属性nameGetProperty 将返回null,所以我使用?. 运算符来防止这种情况发生。

此外,您的原始示例中有一个错字 - 您在 strArr(数组)而不是 strArr[i](字符串)上调用了 Split

XClass instance = new XClass();

for (int i = 0; i < strArr.Length; i++)
{
    var parts = strArr[i].Split(':');
    if (parts.Length < 2) continue;

    var propName = parts[0];
    var propValue = parts[1];

    instance.GetType().GetProperty(propName)?.SetValue(instance, propValue);
}

请注意,此代码将按您提供的示例工作,但propValue 必须是正确的类型(在本例中为string)才能工作。因此应添加额外的错误处理以使这项工作更通用。

【讨论】:

    猜你喜欢
    • 2014-12-19
    • 1970-01-01
    • 2015-08-24
    • 2013-09-25
    • 2016-10-03
    • 1970-01-01
    • 1970-01-01
    • 2019-08-11
    • 2023-04-04
    相关资源
    最近更新 更多