简体   繁体   中英

Use anonymous type in generic class

I have the following class with an Add mapper

public class OrderMapper<T> {
  public OrderMapper<T> Add<TKey>(Expression<Func<T, TKey>> expression, String name) {
  }
}

which I use as follows:

OrderMapper<Post> mapper = new OrderMapper<Post>().Add(x => x.Created, "created");

The problem is that sometimes I have the following:

posts.SelectMany(x => x.Category, (Post, Category) => new { Post, Category });

Which returns a list of anonymous types:

var objects = new { Post post, Category category }

I am not sure how to create an OrderMapper of this type ...

I think maybe I need to change my class method to an extension like:

OrderMapper mapper = objects.Add(...).Add(...)

Could someone tell me the best way to do this?

You can use a Create method for the OrderMapper class :

public class OrderMapper
{
    public static OrderMapper<T> CreateMapperFor<T>(IEnumerable<T> typeProvider)
    {
        return new OrderMapper<T>();
    }
}

And, use it as such :

var objects = Enumerable.Repeat(new { /* ... */ }, 1);
var mapper = OrderMapper.CreateMapperFor(objects)
    .Add(/*...*/)
    .Add(/*...*/);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM