【问题标题】:How to iterate on a T object to find a property?如何迭代 T 对象以查找属性?
【发布时间】:2012-11-23 06:15:25
【问题描述】:

我有这段代码,我目前正在适应使用嵌套实体(实体框架)。我有一个包含 2 个属性的实体,它们是 2 个子实体。

第一步是读取两个类的元数据,从第一个类开始,构建属性列表。这就完成了。现在我需要遍历我的对象以找到执行 DataBinding 的好属性。

这是我目前拥有的:

变量示例:

datasource = namespace.A
propriete = {System.Nullable`1[System.Int32] count} 
propriete.DeclaringType {Name = "prop2" FullName = "Namespace.Metadata.prop2"}

代码:

if (this.datasource != null)
{
    var y = (T)this.datasource;

    var propList = typeof(T).GetProperties();
    if (propList.ToList().Contains(propriete))
    {
        TextBox.Text = DataBinder.Eval(y, propriete.Name).ToString();
    }
    else
    {
        TextBox.Text = ":( need child-support!";
    }
}

我的主要问题是我的对象类型在运行时之前是未知的(类型 T),所以我不知道如何找到我的字段。

快速模型:

Class A {
  public B prop1;
  public C prop2;
}

Class B {
   int count;
   string name;
}

Class C {
   int count;
   string name;
}

A.prop1.count = 1;
A.prop1.name = "a";
A.prop2.count = 2;
A.prop2.name = "b";

现在,我的属性名称都是唯一的(比计数/名称更具体),但我希望它们在某些时候是相同的(计数/名称)。

propriete 可能必须使用 DeclaringType/ReflectedType “过滤”非唯一名称。

考虑唯一名称的蛮力解决方案虽然不优雅,但可能会被接受。

额外问题:propriete 使用另一个包含在 metadata 命名空间中的部分类,而 datasource 使用主类。

(...如果您对该系统的功能感到好奇:它基于基于此 metadata.entity 数据属性的实体构建一个 html 表(带有 .net 控件)。)

【问题讨论】:

  • 你想用IIterable 代替T吗?
  • 你的意思是IIterable<T>?我不知道如何将我的班级类型变成一个列表...

标签: c# nested-class databinder


【解决方案1】:

您可以通过在实例上调用 GetType() 来获取类型信息。所以你的情况是:

var propList = this.datasource.GetType().GetProperties()

【讨论】:

  • 这不是他想要的。
  • 你的建议与我已经拥有的这条线完全相同:var propList = typeof(T).GetProperties();.
  • 你试过了吗?因为这将从实例中获取属性。所以你不需要预先知道类型......
【解决方案2】:

这是我最终得到的结果:

if (this.datasource != null)
{
    var y = (T)this.datasource;

    var propList = typeof(T).GetProperties();
    //try to assign the prop but it might be on a child-prop.
    try 
    {           
        retour = DataBinder.Eval(y, propriete.Name).ToString();
    }
    catch 
    {
        foreach (PropertyInfo prop in propList)
        {
            if ((prop.PropertyType).FullName.Contains("Env."))
            {
                var childPropList = prop.PropertyType.GetProperties();
                foreach (PropertyInfo childProp in childPropList)
                {
                    if (((System.Reflection.MemberInfo)(childProp)).Name == propriete.Name)
                    {
                        var x = DataBinder.GetPropertyValue(y, prop.Name);
                        retour = DataBinder.Eval(x, propriete.Name).ToString();
                    }
                }
            }
        }
    }
}

目前它可以工作,但在不久的将来它可能不够通用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    • 2022-07-14
    • 2015-11-07
    • 2021-06-20
    • 2014-04-09
    • 1970-01-01
    • 2020-05-18
    相关资源
    最近更新 更多