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

本文关键字:参数 操作 执行 动态 | 更新日期: 2023-09-27 18:21:04

下面我有一些方法可以帮助我执行参数化和无参数化操作,而且它很有效。然而,我有一个问题想解决,问题是当我打电话给时

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

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

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

也许使用该方法的非通用和通用版本可以做到这一点:

    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)版本可能也能起到作用…)