[英]EntityCollection<T> to List<T> through Reflection
我使用反射來動態獲取數據(實體類型在運行時定義)。 我當前在我的currentObject沒有1:N關系時(通過“ First”通用方法反射實現),當前返回一個對象,但是我還需要獲取1:N子對象,即EntityCollection <T>。
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>;
}
}
事實是我的“ valoresp”變量可以是480種不同的EntityCollection類型(這就是為什么我不手動檢查類型的原因)(EntityCollection <table1>,EntityCollection <Table2> ...)
我需要子對象的列表,但是找不到使用反射將EntityCollection轉換為List的方法。
剛剛想出了如何:
不要嘗試強制轉換為EntityCollection,而是先檢查它是否可枚舉(因為EntityCollection實現IEnumerable)並強制轉換為Enumerable。
然后,您將能夠使用Linq查詢,方法等...,而且避免轉換為List( 但您仍然可以,因為IEnumerable具有.ToList()方法 )
if (valoresp is IEnumerable<object>)
{
var valorEnum = valoresp as IEnumerable<object>;
...
//valorEnum.First / valorEnum.where(...) etc..
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.