我正在编写一个异步类来简化函数操作。以下是我的代码:
using System;
namespace AsyncLibery
{
public class AsyncLibery
{
delegate void Exec(); // No input parameter, no return value
delegate void ExecWithParams<T>(T T1); //One input parameter, no return value
delegate void ExecWithParams<T1, T2>(T1 t1,T2 t2); //Two input parameters, no return value
delegate void ExecWithParams<T1, T2, T3>(T1 t1, T2 t2, T3 t3);//Three input parameters, no return value
delegate void ExecWithParams<T1, T2, T3, T4>(T1 t1, T2 t2, T3 t3, T4 t4);//Four input parameters,no return value
delegate T ExecWithReturnType<T>(); //No input parameter, one return value
delegate T2 ExecWithReturnType<T1, T2>(T1 t1); //One input parameter, one return value
delegate T3 ExecWithReturnType<T1, T2, T3>(T1 t1, T2 t2);//Two input parameters, one return value
delegate T4 ExecWithReturnType<T1, T2, T3, T4>(T1 t1, T2 t2, T3 t3);//Three input parameters, one return value
delegate T5 ExecWithReturnType<T1, T2, T3, T4, T5>(T1 t1, T2 t2, T3 t3, T4 t4);// Four input parameters, one return value.
#region no input parameter, no return value
public void BeginInvokeEx(Action actionFunction)
{
Exec exec = new Exec(actionFunction);
exec.BeginInvoke(new AsyncCallback(EndInvokeEx), exec);
}
private void EndInvokeEx(IAsyncResult iar)
{
Exec exec = (Exec)iar.AsyncState;
exec.EndInvoke(iar);
}
#endregion
#region one input parameter, no return value
public void BeginInvokeEx<T>(Action<T> actionFunction,T T1)
{
ExecWithParams<T> exec = new ExecWithParams<T>(actionFunction);
exec.BeginInvoke(T1, new AsyncCallback(EndInvokeEx1), exec);
}
private void EndInvokeEx1(IAsyncResult iar)
{
ExecWithParams<T> exec = (ExecWithParams<T>)iar.AsyncState;
exec.EndInvoke(iar);
}
#endregion
}
}
当我编写代码时,它会抛出一个异常,例如“找不到类型或命名空间名称'T'(你是否缺少using指令或程序集引用?)”,例外情况出现在下面的代码中:
ExecWithParams<T> exec = (ExecWithParams<T>)iar.AsyncState;
我知道我们必须引用T参数特定类型,如int或string或其他任何东西。 但是谁可以帮助我而不修改T参数?有什么好方法可以解决吗? THX。
答案 0 :(得分:2)
让EndInvokeEx1
通用:
private void EndInvokeEx1<T>(IAsyncResult iar)
{
ExecWithParams<T> exec = (ExecWithParams<T>)iar.AsyncState;
exec.EndInvoke(iar);
}
相应地更改BeginInvokeEx
:
public void BeginInvokeEx<T>(Action<T> actionFunction,T T1)
{
ExecWithParams<T> exec = new ExecWithParams<T>(actionFunction);
exec.BeginInvoke(T1, new AsyncCallback(EndInvokeEx1<T>), exec);
}
答案 1 :(得分:1)
您尚未定义T
是什么。您需要在方法EndInvokeEx1
上具有通用参数,使其变为EndInvokeEx<T>
,然后您可以将T
传递给演员。否则,它将需要在类声明中定义,因此您的类声明变为public class AsyncLibrary<T>
。否则,编译器将不知道T
代表什么。