Simulate variadic templates in C#

前端 未结 6 949
轮回少年
轮回少年 2020-12-09 14:57

Is there a well-known way for simulating the variadic template feature in C#?

For instance, I\'d like to write a method that takes a lambda with an arbitrary set of p

6条回答
  •  心在旅途
    2020-12-09 15:35

    Another alternative besides those mentioned above is to use Tuple<,> and reflection, for example:

    class PrintVariadic
    {
        public T Value { get; set; }
    
        public void Print()
        {
            InnerPrint(Value);
        }
    
        static void InnerPrint(Tn t)
        {
            var type = t.GetType();
            if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Tuple<,>))
            {
                var i1 = type.GetProperty("Item1").GetValue(t, new object[]{});
                var i2 = type.GetProperty("Item2").GetValue(t, new object[]{ });
                InnerPrint(i1);
                InnerPrint(i2);
                return;
            }
            Console.WriteLine(t.GetType());
        }
    }
    
    class Program
    {
        static void Main(string[] args)
        {
            var v = new PrintVariadic>>>();
            v.Value = Tuple.Create(
                1, Tuple.Create(
                "s", Tuple.Create(
                4.0, 
                4L)));
            v.Print();
            Console.ReadKey();
        }
    }
    

提交回复
热议问题