我的问题:我需要设置 5 个属性,除了几个参数之外,每个属性的代码都是相同的。因此,我不想为每个参数编写重复的代码,而是想尝试反射来设置所有参数的值。
这些属性位于运行此代码的同一个类中,例如:
public MyClass
{
public string? L1Value { get; set; }
public string? L2Value { get; set; }
public string? L3Value { get; set; }
public string? L4Value { get; set; }
public string? L5Value { get; set; }
public void MethodToGetProperty()
{
var result = GetType().GetPropterty(L1Value);
}
}
**在我的实际代码中,我有一个 FOR 循环,它将动态创建参数字符串名称。但是,我必须让这个
GetProperties()
发挥作用。
GetProperty(L1Value)
返回 null。我使用了 GetType().GetProperties()
,我看到了所有属性,并且 L1Value 有一个值。
我发现 Stackoverflow 中的问题都指向 1)它是一个字段,而不是属性(没有 getter 或 setter)或 2)访问修饰符不正确或丢失。这些都不适用于此。
我很感激您的任何建议。
在
GetProperty
方法中,您需要传入所需属性的名称。例如:
var result = GetType().GetProperty("L1Value");
或者:
var result = GetType().GetProperty(nameof(L1Value));
注意这只会给你
PropertyInfo
对象,所以如果你想要实际值,你需要这样做:
var value = result.GetValue(this);