[英]How can get the type of nested generic type
有一個像這樣的第三方組件庫:
public static class GenericExcuteTestClassExtension
{
public static void Excute<T>(this GenericExcuteTestClass clazz,
string parameter, Action<ReturnClass<T>> callback)
{
ReturnClass<T> rClazz = new ReturnClass<T>(parameter);
rClazz.Property5 = typeof(T).ToString();
callback.Invoke(rClazz);
}
public static void Excute<T>(this GenericExcuteTestClass clazz,
string parameter, Action<ReturnClass> callback)
{
ReturnClass rClazz = new ReturnClass(parameter);
rClazz.Property5 = typeof(T).ToString();
callback.Invoke(rClazz);
}
}
我想反思調用方法Excute<T>(this GenericExcuteTestClass clazz, string parameter, Action<ReturnClass<T>> callback)
。
我使用typeof(GenericExcuteTestClassExtension).GetMethod("Excute", new Type[] { typeof(GenericExcuteTestClass), typeof(string), typeof(Action<ReturnClass<>>)})
,但編譯器得到錯誤“Type expected ”。 我如何獲得(Action<ReturnClass<>>)
, Action<>
可以編譯,但這不是我的期望。
我想將一個自定義action<ReturnClass<>>
像(result)=>{....}
傳遞給方法,我該怎么辦呢?
請幫忙,謝謝。
為什么我用reflect來執行這個?
因為此方法必須在aop攔截中執行
這種真實情況是這樣的:
我想在我的應用程序中使用restsharp,並編寫一個類似的界面
[RestfulService(Constants.BASE_URL + "/login")]
public interface UserService
{
[Request("/login")]
void Login([Paramter] string name, [Paramter] string password, Action<T> callBack);
}
並截取接口以獲取參數以執行restsharp ExecuteAsync<T>(this IRestClient client, IRestRequest request, Action<IRestResponse<T>> callback)
以獲取數據。
所以我需要將UserService中的T
傳遞給public void Intercept(IInvocation invocation) of castle.windsor
Intercept方法public void Intercept(IInvocation invocation) of castle.windsor
ExecuteAsync<T>
,在這個方法體中,我們只能得到GenericType的Type cannnot get T,所以如果我直接調用ExecuteAsync
,我無法將GenericType T傳遞給此方法。 我必須這樣使用: ...GetMethod("...").MakeGenericType(new Type[]{piLast.ParameterType.GenericTypeArguments})
整個問題來自於嵌套泛型類型在.NET中的反射系統沒有得到很好的處理。
在您的情況下,最簡單的解決方案是自己過濾方法。 一個快速和臟的片段:
MethodInfo method = null;
foreach (var m in typeof(GenericExcuteTestClassExtension)
.GetMethods(BindingFlags.Public | BindingFlags.Static))
{
var parameters = m.GetParameters();
if (!parameters.Any())
continue;
var lastParameterType = parameters.Last().ParameterType;
var genericArgument = lastParameterType
.GetGenericArguments()
.SingleOrDefault();
// you can/should add more checks, using the Name for example
if (genericArgument != null && genericArgument.IsGenericType)
{
method = m;
break;
}
}
你應該從中做出一個實用的方法。 可以在此處找到允許搜索具有嵌套泛型的任何方法的一般方法。 在這里使用Expressions
還有另一種可能性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.