【发布时间】:2013-07-03 13:56:05
【问题描述】:
下面我有一些方法可以帮助我执行有参数和无参数的操作,并且它有效。 但是我有一个问题想解决,问题是当我打电话时
Execute<Action<Myclass>, Myclass>(ActionWithParameter);
我通过了MyClass 2 次。第一次定义我的操作ActionWithParameter 所需的参数,第二次定义我在Execute<TAction, TType> 方法中期望的参数类型。
所以我的问题是:有没有办法摆脱第二个通用 TType 并以某种方式从第一个通用 TAction 中获取它?
也许像TAction<TType>?
class Program
{
static void Main(string[] args)
{
Execute<Action>(ActionWithoutParameter);
Execute<Action<Myclass>, Myclass>(ActionWithParameter);
Console.ReadLine();
}
private static void ActionWithoutParameter()
{
Console.WriteLine("executed no parameter");
}
private static void ActionWithParameter(Myclass number)
{
Console.WriteLine("executed no parameter " + number.ID);
}
private static void Execute<TAction>(TAction OnSuccess)
{
Execute<TAction, Myclass>(OnSuccess);
}
private static void Execute<TAction, TType>(TAction OnSuccess)
{
if (OnSuccess is Action)
{
Action method = OnSuccess as Action;
method();
}
else if (OnSuccess is Action<TType>)
{
Myclass myclass = new Myclass() { ID = 123 };
TType result = (TType)(object)myclass;
Action<TType> method = OnSuccess as Action<TType>;
method(result);
}
}
【问题讨论】:
-
我建议选择一个标签替换为语言标签,这样会得到更多的关注。
-
我现在添加了 c# 作为标签。感谢您的建议
标签: c# generics dynamic parameters action