代码之家  ›  专栏  ›  技术社区  ›  USMC6072

GetProperty()返回null

  •  0
  • USMC6072  · 技术社区  · 2 年前

    我的问题是:我有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)访问修饰符不正确或丢失。这两者都不适用于此。

    enter image description here

    我感谢你的任何建议。

    1 回复  |  直到 2 年前
        1
  •  2
  •   DavidG    2 年前

    GetProperty 方法,需要传入所需属性的名称。例如:

    var result = GetType().GetProperty("L1Value");
    

    或者:

    var result = GetType().GetProperty(nameof(L1Value));
    

    请注意,这只会给您 PropertyInfo 对象,因此如果您想要实际值,则需要执行以下操作:

    var value = result.GetValue(this);