Func<> with unknown number of parameters

前端 未结 6 1550
独厮守ぢ
独厮守ぢ 2020-12-06 00:37

Consider the following pseudo code:

TResult Foo(Func f, params object[] args)
{
    TResult result = f(args);
           


        
6条回答
  •  日久生厌
    2020-12-06 01:06

    In some cases you may be able to get away with a trick like this:

    public static class MyClass
    {
        private static T CommonWorkMethod(Func wishMultipleArgsFunc)
        {
            // ... do common preparation
            T returnValue = wishMultipleArgsFunc();
            // ... do common cleanup
            return returnValue;
        }
    
        public static int DoCommonWorkNoParams() => CommonWorkMethod(ProduceIntWithNoParams);
        public static long DoCommonWorkWithLong(long p1) => CommonWorkMethod(() => ProcessOneLong(p1));
        public static string DoCommonWorkWith2Params(int p1, long p2) => CommonWorkMethod(() => ConvertToCollatedString(p1, p2));
    
        private static int ProduceIntWithNoParams() { return 5; }
    }
    

提交回复
热议问题