Skip to main content
 首页 » 编程设计

c#之通过反射访问/执行通用方法

2024年02月05日13softidea

我正在尝试在使用 EF6 时在运行时动态切换表注释的架构值。

到目前为止,这是我得到的:

var builder = new DbModelBuilder() 
var dbSetProperties = typeof(T).GetProperties().Where(p => p.PropertyType.GetGenericTypeDefinition() == typeof(DbSet<>)); 
 
foreach (PropertyInfo property in dbSetProperties) 
{ 
    Type[] propTypes = property.PropertyType.GetGenericArguments(); 
 
    // Iterate the DbSets and set the correct schema 
    foreach (Type dbSetType in propTypes) 
    { 
        // Get the TableAttribute 
        var tableAttribute = Attribute.GetCustomAttribute(dbSetType, typeof(TableAttribute)); 
 
        MethodInfo dbModelMethodInfo = typeof(DbModelBuilder).GetMethod("Entity"); 
        MethodInfo entityTypeConfigMethodInfo = typeof(EntityTypeConfiguration<>).GetMethod("ToTable", new[] { typeof(String), typeof(String) }); 
        MethodInfo genericDbModelMethodInfo = dbModelMethodInfo.MakeGenericMethod(dbSetType); 
 
        genericDbModelMethodInfo.Invoke(builder, null); 
        entityTypeConfigMethodInfo.Invoke(genericDbModelMethodInfo, new Object[] { (tableAttribute as TableAttribute).Name, "NEW_SCHEMA_VALUE" }); 
    } 
} 

我想要完成的是这样的事情(这是行不通的):

builder.Entity<dbSetType>().ToTable((tableAttribute as TableAttribute).Name, "NEW_SCHEMA_VALUE"); 

基本上,对于 T,我想提取 DbSet,确定 Entity<> 泛型中使用的类,获取 TableAttribute,并将架构设置为新值。

目前,在 entityTypeConfigMethodInfo.Invoke 上,我收到错误消息“无法对 ContainsGenericParameters 为真的类型或方法执行后期绑定(bind)操作”。

我错过了什么?

请您参考如下方法:

嗯,是的,你期待什么?

你说你在这一行得到了错误:

entityTypeConfigMethodInfo.Invoke(genericDbModelMethodInfo, new Object[] { (tableAttribute as TableAttribute).Name, "NEW_SCHEMA_VALUE" }); 

问题不在于这一行,而在于这一行:

MethodInfo entityTypeConfigMethodInfo = typeof(EntityTypeConfiguration<>).GetMethod("ToTable", new[] { typeof(String), typeof(String) }); 

您正在获取哪种类型的方法ToTable?

包含该方法的类型仍然是一个开放的泛型类型。您必须指定类型参数以使其成为特定类型,然后您才能获取要调用的方法。

换句话说,你需要这个:

MethodInfo entityTypeConfigMethodInfo = 
    typeof(EntityTypeConfiguration<>).MakeGenericType(...).GetMethod("ToTable", new[] { typeof(String), typeof(String) }); 
                                     ^-------------------^