EntityCollection< T>List< T>通过反射

本文关键字:反射 List EntityCollection | 更新日期: 2023-09-27 18:15:17

我使用反射来动态获取数据(实体类型在运行时定义)。我目前返回一个对象每当我的currentObject没有1:N关系(通过"第一"通用方法反射实现),但我需要得到也1:N子,那是EntityCollection

var valoresp = getFilho(pai, filho, raizAtual);
        if (valoresp == null)
            return new object();
 if (!filho.A_Ocorrencia_Tabela.Contains("1:N"))
        {
            var firstMethod = typeof(Enumerable).GetMethods().Single(method => method.Name == "First"
                              && method.IsStatic && method.GetParameters().Length == 1);
            var interfaceImplementation = MethodResolver.GetImplementationOfInterface(valoresp.GetType(),
                              firstMethod.GetParameters().First().ParameterType.GetGenericTypeDefinition());
            var genericArgumentsTypes = interfaceImplementation.GetGenericArguments();
            var genericMethod = firstMethod.MakeGenericMethod(new[] { genericArgumentsTypes[0] });
            try
            {
                var resultado = genericMethod.Invoke(null, new[] { valoresp });
                return resultado;
            }
            catch (Exception)
            {
                return new object();
            }
        }
        else
        {
            if (valoresp.GetType().IsGenericType && (valoresp.GetType().GetGenericTypeDefinition()  == typeof(EntityCollection<>))  )
            {
                   //here is the problem:
                   var typeValoresp = valoresp as EntityCollection<object>;

            }
        }

事实是我的"valorep"变量可以是480种不同类型的EntityCollection(这就是为什么我不会手动检查类型)(EntityCollection<表1>,EntityCollection<</p>

我需要一个子对象的列表,但无法找到一种方法将EntityCollection转换为使用反射的列表。

EntityCollection< T>List< T>通过反射

刚刚知道如何:

与其尝试转换为EntityCollection,不如先检查它是否是可枚举的(因为EntityCollection实现了IEnumerable),然后转换为enumerable。

然后你将能够使用Linq查询,方法等…另外,避免强制转换为List(),但你仍然可以,因为IEnumerable有.ToList() Method)

if (valoresp is IEnumerable<object>)
{
    var valorEnum = valoresp as IEnumerable<object>;
    ...
    //valorEnum.First / valorEnum.where(...) etc..
}