动态参数化和无参数动作执行

时间:2013-07-03 13:56:05

标签: c# generics dynamic parameters action

下面我有一些方法可以帮助我执行参数化和无参数的操作,并且它可以工作。 但是我有一个问题,我想摆脱,问题是,当我打电话

Execute<Action<Myclass>, Myclass>(ActionWithParameter); 

我通过了MyClass 2次。第一次定义我的Action 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);
            }
        }

1 个答案:

答案 0 :(得分:0)

使用该方法的非泛型和通用版本可以解决这个问题:

    public static void Execute<TType>(Action<TType> OnSuccess) 
         where TType : Myclass // gets rid of unnecessary type-casts - or you just use Action<Myclass> directly - without the generic parameter...
    { 
         // throw an exception or just do nothing - it's up to you...
         if (OnSuccess == null)
             throw new ArgumentNullException("OnSuccess"); // return;

         TType result = new Myclass() { ID = 123 };
         OnSuccess(result);
    }

    public static void Execute(Action OnSuccess) 
    { 
        if (OnSuccess == null)
            throw new ArgumentNullException(); // return;

        OnSuccess();            
    }

(但是我不太确定结果生成+动作执行的目的 - 只使用非通用的Execute(Action)版本也可以做到这一点......)