簡體   English   中英

是否可以通過反射調用“選擇”方法

[英]Is it possible to invoke “Select” method via reflection

我正在研究一個項目,我遇到的情況是我需要從可查詢對象中“選擇”數據。 不幸的是,我無法知道實際可查詢對象在編譯時的類型。 所以我嘗試通過反射調用“select”方法。 我到目前為止嘗試的代碼如下。

....
.......
//suppose that I've got TSource and TResult at runtime.
Type argumentType = Model.GetArgumentType();

//get a queryable object from modle.
IEnumerable obj   = Model.GetQueryableObject(); 

//looking for Select<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TResult> selector);
var selectMethod = typeof(System.Linq.Enumerable)
                  .GetMethods(BindingFlags.Static | BindingFlags.Public)
                  .Where(mi => mi.Name == "Select" &&                            
                               mi.GetParameters()[1].ParameterType.GetGenericArguments().Count() == 2)
                  .Single()
                  .MakeGenericMethod(new Type[] { argumentType, argumentType });

//that is where I have no idea how to do it
var result = selectMethod.Invoke(null, new object[] { obj, **xxxxxx** });
....
...

任何人都可以告訴我如何通過反射調用“選擇”方法為selectMethod制作一個“ Func<TSource, TResult> ”? 謝謝。




更新:正如@Jon Skeet所說。 示例代碼中有幾個錯誤。 顯然,我可能會以錯誤的方式提出問題(這絕對是我的錯)。 因此我決定修改原始問題以使其更清楚(或更糟)。 希望有所幫助。

(這個答案曾經只是一個評論。)

它會是這樣的

Type funcType = typeof(Func<,>).MakeGenericType(argumentType, argumentType);

(在實際情況下,你可能不希望TSourceTResult一樣。)

之后,使用您的funcType調用Delegate.CreateDelegate以及您想要添加到新Delegate.CreateDelegate “select function”。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM