How do I create and access a new instance of an Anonymous Class passed as a parameter in C#?

后端 未结 4 385
悲&欢浪女
悲&欢浪女 2020-12-14 12:00

I have created a function that takes a SQL command and produces output that can then be used to fill a List of class instances. The code works great. I\'ve included a slig

4条回答
  •  生来不讨喜
    2020-12-14 12:18

    This method stores one line of a sql query in a variable of anonymous type. You have to pass a prototype to the method. If any property of the anonymous type can not be found within the sql query, it is filled with the prototype-value. C# creates constructors for its anonymous classes, the parameters have the same names as the (read-only) properties.

        public static T GetValuesAs(this SqlDataReader Reader, T prototype)
        {
            System.Reflection.ConstructorInfo constructor = prototype.GetType().GetConstructors()[0];
            object[] paramValues = constructor.GetParameters().Select(
                p => { try               { return Reader[p.Name]; }
                       catch (Exception) { return prototype.GetType().GetProperty(p.Name).GetValue(prototype); } }
                ).ToArray();
            return (T)prototype.GetType().GetConstructors()[0].Invoke(paramValues);
        }
    

提交回复
热议问题