【发布时间】:2019-06-19 23:28:13
【问题描述】:
假设strArr 是一个字符串数组。在一个循环中,我将它们中的每一个分开,因此我可以获得 key 和 value。我要做的就是在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