开发者

Help me understand NewExpression.Members

开发者 https://www.devze.com 2023-01-20 02:38 出处:网络
Does NewExpression.Members inform the LINQ runtime how to map a type\'s constructor parameters to its properties? And if so, is there an attribute to set the mapping? I\'m imagining something like thi

Does NewExpression.Members inform the LINQ runtime how to map a type's constructor parameters to its properties? And if so, is there an attribute to set the mapping? I'm imagining something like this:

public class Customer
{
  public Customer(int id, string name)
  {
    Id = id;
    Name = name;
  }

  [Ctor开发者_如何学JAVAParam("id")]
  public int Id { get; set; }

  [CtorParam("name")]
  public string Name { get; set; }
}

But none of the MSDN docs really inform you how exactly Members is initialized.


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

So this is fine:

        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 do need them, I would expect them to be positional relative to the "arguments" expressions - so you would pass in (in an array) the member for id and name. Note that there is also a separate expression for intialzer-style binding.

0

精彩评论

暂无评论...
验证码 换一张
取 消