简体   繁体   English

创建泛型类型的实例

[英]Create an instance of generic Type

I have the following: 我有以下几点:

ModelBuilder builder = new ModelBuilder();
builder.Entity<Model>().Add(new ModelMapper());

Instead I would like to use it as follows: 相反,我想按如下方式使用它:

ModelBuilder builder = new ModelBuilder();
builder.Add<ModelMapper>();

So the ModelBuilder Add extension would create a new instance of T and add it to builder.Entity().Add(new T); 因此,ModelBuilder Add扩展将创建T的新实例,并将其添加到builder.Entity()。Add(new T);

How can I do this? 我怎样才能做到这一点?

This should do the job using a combination of type constraints. 这应该结合使用类型约束来完成。 You may want to make this an extension method. 您可能需要将此作为扩展方法。

public void Add<TEntity, TMapper>() 
    where TEntity : class
    where TMapper : EntityMapper<TEntity>, new()
{
    this.Entity<TEntity>().Add(new TMapper());
}

And use it like this: 并像这样使用它:

builder.Add<Model, ModelMapper>();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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