[英]Unable to cast reflection called method type IEnumerable<Tuple>
當我在反射中調用方法時出現錯誤,我無法將結果轉換為其基本類型(IEnumerable<Tuple<SortingOrder, Expression>>)
,這看起來很奇怪。
當我在 Expression 中轉換另一種方法時,我沒有這個問題。 我想問題出在 IEnumerable 或 Tuple 上。 有誰知道如何做到這一點?
當我調用下面的第一個方法時出錯:
public static IEnumerable<Tuple<SortingOrder, Expression>> ConvertOrderByToTupleExpression(Type entityType, string orderBy)
{
return (IEnumerable<Tuple<SortingOrder, Expression>>)typeof(RepositoryReflectionHelper)
.GetMethods()
.First(x => x.Name == nameof(RepositoryReflectionHelper.ConvertOrderByToTupleExpression) && x.IsGenericMethod && x.GetParameters().Count() == 1)
.MakeGenericMethod(new Type[] { entityType })
.Invoke(null, new object[] { orderBy });
}
public static IEnumerable<Tuple<SortingOrder, Expression<Func<TEntity, object>>>> ConvertOrderByToTupleExpression<TEntity>(string orderBy)
{
List<Tuple<SortingOrder, Expression<Func<TEntity, object>>>> orderByCriteriaTuple = new List<Tuple<SortingOrder, Expression<Func<TEntity, object>>>>();
return orderByCriteriaTuple;
}
感謝你的時光
C# 不支持類的變化,但您可以利用它支持接口變化的事實, IEnumerable<T>
是協變接口, Tuple<T1, T2>
實現ITuple
:
object tuple = new[]
{
new Tuple<int, Expression<Func<int>>>(1, () => 1)
};
IEnumerable<Tuple<int, Expression>> enumerable = ((IEnumerable<ITuple>)tuple)
.Select(t => Tuple.Create((int)t[0], (Expression) t[1]))
.ToList(); // to list to make sure it does work
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.