简体   繁体   English

方法调用通过反射检索的变量类型

[英]Method calls on variable type retrieved through reflection

As part of an effort to create a workaround for an earlier problem , I have a list of Type on which I (in a perfect world) want to execute the following code: 作为为早期问题创建解决方法的努力的一部分,我有一个Type列表,我(在一个完美的世界中)想要执行以下代码:

foreach (Type entityType in entityTypes)
{
    modelBuilder.Entity<entityType>()
        .Map(m => m.Requires("Deleted").HasValue(false))
        .Ignore(m => m.Deleted);
}

Obviously, because we can't use variable types this way, I have to use reflection. 显然,因为我们不能以这种方式使用变量类型,所以我必须使用反射。 So far, I am able to call up to the first method .Entity() : 到目前为止,我能够调用第一个方法.Entity()

foreach (Type entityType in entityTypes)
{
    var modelEntity = typeof (DbModelBuilder)
        .GetMethod("Entity")
        .MakeGenericMethod(new[] {entityType})
        .Invoke(modelBuilder, null);
}

However, I still need to call .Map() and .Ignore() on modelEntity , which is of type EntityTypeConfiguration<T> . 但是,我仍然需要在modelEntity上调用.Map().Ignore() ,它的类型为EntityTypeConfiguration<T> This is where my issue lies, because I do know (at runtime) that T is of type entityType , but I cannot simply call the following code: 这就是我的问题所在,因为我知道(在运行时) TentityType类型,但我不能简单地调用以下代码:

foreach (Type entityType in entityTypes)
{
    var modelEntity = typeof (DbModelBuilder)
        .GetMethod("Entity")
        .MakeGenericMethod(new[] {entityType})
        .Invoke(modelBuilder, null);

    var mappedEntity = typeof (EntityTypeConfiguration<entityType>)
        .GetMethod("Map")
        .MakeGenericMethod(new[] {entityType})
        .Invoke(modelEntity, <parameters>);
}

Because I again have the same problem why I used reflection to call .Entity() in the first place. 因为我再次.Entity()同样的问题,为什么我首先使用反射来调用.Entity() Can I again use reflection to call both methods, or can I use an other way to call them directly on modelEntity ? 我可以再次使用反射来调用这两种方法,还是可以使用其他方法直接在modelEntity上调用它们?

One way to work around this issue is to make a generic method of your own to combine three calls into one, and use reflection to call your method, like this: 解决此问题的一种方法是创建自己的通用方法,将三个调用合并为一个,并使用反射调用您的方法,如下所示:

void LoopBody<T>() { // Give the method a better name
    modelBuilder.Entity<T>()
        .Map(m => m.Requires("Deleted").HasValue(false))
        .Ignore(m => m.Deleted);
}

Now you can call this method from your loop: 现在您可以从循环中调用此方法:

foreach (Type entityType in entityTypes) {
    GetType().GetMethod("LoopBody")
        .MakeGenericMethod(new[] { entityType })
        .Invoke(this, null);
}

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

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