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

如何从基本抽象类访问类属性

  •  1
  • JBryanB  · 技术社区  · 1 年前

    我正在尝试设计一个抽象基类,它可以从继承自它的类中收集所有属性。我对名称很好,但获取值不起作用。我得到运行时错误“对象与目标不匹配”。非常感谢您的帮助。

     public string Get()
        {
            string ret = "";
            var type = GetType();
            foreach (PropertyInfo p in this.GetType().GetProperties())
            {
                 ret += p.Name + "`" + p.GetValue(type) + "~";
                //i've also tried
                //ret += p.Name + "`" + p.GetValue(this) + "~";
            }
    
            ret = ret.TrimEnd('~');
            return ret;
        }
    
    3 回复  |  直到 1 年前
        1
  •  3
  •   Guru Stron    1 年前

    参数计数不匹配。

    其中一个属性似乎是 indexer ,可以通过检查忽略这些属性 GetIndexParameters PropertyInfo (或根据需要进行相应处理):

    if (!p.GetIndexParameters().Any())
    {
        ret += p.Name + "`" + p.GetValue(this) + "~";
    }
    

    带有运行时异常的演示 @sharplab.io

        2
  •  2
  •   Yehor Androsov    1 年前

    您需要传递要从中获取属性值的对象

    p.GetValue(this)

        3
  •  1
  •   Guru Stron    1 年前

    使用时 任意的 课程,我们应该考虑,我们可以

    • static 属性: public static int MyId => 3;
    • 索引器 public int this[int index] { get => index;}
    • 仅写入 特性 public int MyId {set => m_Id = value;}

    到目前为止还不错,让我们 查询 属性:

    using System.Linq;
    
    ...
    
    public string Get() => string.Join("~", GetType()
      .GetProperties()
      .Where(prop => prop.CanRead)                            // readable
      .Where(prop => !prop.GetGetMethod().IsStatic)           // instance  
      .Where(prop => prop.GetIndexParameters().Length == 0)   // not an indexer
      .Select(prop => $"{prop.Name} `{prop.GetValue(this)}"));
    

    另一个问题是 字符串操作 :如果你有很多房产(长 ret )添加字符串可以 缓慢的 .如果你愿意 参加 字符串,只需放入 string.Join