从PropertyInfo获取复杂的类型属性

时间:2018-08-02 18:51:34

标签: c# system.reflection

我试图构建一个通用的递归函数来迭代所有属性/复杂属性,并从以下structre返回所有属性的数组:

public class Root
{
   [FieldCodeItems(1, EnumFieldCode.INT, "ED", "0204")]
   public int Prop1 { get; set; }
   public Child Child { get; set; }
}
public class Child
{
    [FieldCodeItems(1, EnumFieldCode.INT, "ED", "0208")]
    public int PropChild1 { get; set; }
    [FieldCodeItems(19, EnumFieldCode.ALPHANUMERIC, "ED", "0208")]
    public string PropChild2 { get; set; }
    public Child1 Child1 { get; set; }
}

public class Child1
{
    [FieldCodeItems(1, EnumFieldCode.INT, "ED", "0211")]
    public int PropChild3 { get; set; }
}

public class MyReturClass
{
    public string FileCode { get; set; }
    public string FieldCode { get; set; }
}

我可以从Root类读取所有属性,但无法从复杂属性中获取属性:

public static List<MyReturClass> GetItems<T>(T obj)
{
    var ret = new List<MyReturClass>();

    PropertyInfo[] properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
    foreach (PropertyInfo property in properties)
    {
        IEnumerable<Attribute> attributes = property.GetCustomAttributes();
        foreach (Attribute attribute in attributes)
        {
            //here I read values from a custom property
            var tr = (FieldCodeItems)attribute;
            var value = obj.GetType().GetProperty(property.Name).GetValue(obj, null);

            if (value == null) continue;

            ret.Add(new MyReturClass
            {
                FieldCode = tr.FieldCode,
                FileCode = tr.FileCode
            });     
        }
        //If is complex object (Child, Child1 etc)
        if (property.PropertyType.IsClass && property.PropertyType != typeof(string))
        {
            //I would like pass the complex property as parameter, but at this moment 
            //the property variable is a PropertyInfo and I need the complex type
            //to get properties values from this object
            GetItems(property); //Error. Also tried with GetItems(property.PropertyType);
        }
    }

    return ret;
}

我想将复杂的属性作为参数传递,但是目前,属性变量是PropertyInfo,我需要复杂的类型才能从此对象获取属性值。 我如何获得这个物体?

我搜索了hereherehere,但是解决方案无法解决我的问题。

编辑-2018年3月8日

最后我找到了here

我添加了以下代码来解决问题:

//If is complex object (Child, Child1 etc)
if (property.PropertyType.IsClass && property.PropertyType != typeof(string))
{
    if (obj == null) { return null; }

    Type type = obj.GetType();
    PropertyInfo info = type.GetProperty(property.Name);

    if (info == null) { return null; }
    var v = info.GetValue(obj, null);

    if (v != null)
        GetItems(v);
}

1 个答案:

答案 0 :(得分:0)

看看https://docs.microsoft.com/en-us/dotnet/framework/reflection-and-codedom/how-to-examine-and-instantiate-generic-types-with-reflection

我不确定您要寻找的内容是否会正常工作,因为在您的EF中,您将类配置为ComplexType。我不确定类本身是否知道其complexType。您可能最终会在DBcontext上创建方法...

相关问题