Help me understand NewExpression.Members

Does NewExpression.Members tell LINQ runtime how to map type constructor parameters to its properties? And if so, is there an attribute to customize the display? I imagine something like this:

public class Customer { public Customer(int id, string name) { Id = id; Name = name; } [CtorParam("id")] public int Id { get; set; } [CtorParam("name")] public string Name { get; set; } } 

But not one of the MSDN docs tells you exactly how members are initialized.

+4
source share
1 answer

My limited understanding is that you usually don't need to pass on member information; arguments are taken (by position) from the arguments parameter. Member information (I suspect), intended to help some internal APIs when you are dealing with things like anonymous types that look (in C #) how they are initialized by a member (like an object initializer), but which are actually initialized constructor, This means that things like LINQ-to-SQL will see the use of constcutor, and then (in the next part of the query) access to obj.Name - it needs a way to understand what this means "the third parameter for the constructor (which never really called.) In particular and, for things like groupings.

So this is great:

  var param = Expression.Parameter(typeof(string), "name"); var body = Expression.New(typeof(Customer).GetConstructor(new[] {typeof(int), typeof(string)}), Expression.Constant(1), param); var func = Expression.Lambda<Func<string, Customer>>(body, param).Compile(); var cust = func("abc"); 

If you need them, I would expect them to be positional relative to the "arguments" expressions, so you must pass (in an array) the member for id and name. Note that there is also a separate expression for binding an intialzer style.

+5
source

All Articles