How to create an anonymous object with property names determined dynamically?

后端 未结 3 517
隐瞒了意图╮
隐瞒了意图╮ 2021-02-01 22:56

Given an array of values, I would like to create an anonymous object with properties based on these values. The property names would be simply \"pN\" where N

3条回答
  •  说谎
    说谎 (楼主)
    2021-02-01 23:06

    Not exactly an anonymous object, but what about implementing a DynamicObject which returns values for p1 ... pn based on the values in the array? Would that work with Dapper?

    Example:

    using System;
    using System.Dynamic;
    using System.Text.RegularExpressions;
    
    class DynamicParameter : DynamicObject {
    
        object[] _p;
    
        public DynamicParameter(params object[] p) {
            _p = p;
        }
    
        public override bool TryGetMember(GetMemberBinder binder, out object result) {
            Match m = Regex.Match(binder.Name, @"^p(\d+)$");
            if (m.Success) {
                int index = int.Parse(m.Groups[1].Value);
                if (index < _p.Length) {
                    result = _p[index];
                    return true;
                }
            }
            return base.TryGetMember(binder, out result);
        }
    
    }
    
    class Program {
        static void Main(string[] args) {
            dynamic d1 = new DynamicParameter(123, "test");
            Console.WriteLine(d1.p0);
            Console.WriteLine(d1.p1);
        }
    }
    

提交回复
热议问题