将PropertyInfo转换为通用类型 [英] Cast PropertyInfo to generic type

查看:1291
本文介绍了将PropertyInfo转换为通用类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下类:

public class AuthContext : DbContext
{
    public DbSet<Models.Permission> Permissions { get; set; }
    public DbSet<Models.Application> Applications { get; set; }
    public DbSet<Models.Employee> Employees { get; set; } 
    // ...
}

我创建了扩展方法对于类型 DbSet< T> 的Clear()。使用反射我能够检查 AuthContext 的实例,并读取类型 DbSet 的所有属性为 PropertyInfo []。如何将 PropertyInfo 转换为 DbSet 以便调用其上的扩展方法?

I created the extension method Clear() for type DbSet<T>. Using reflection I am able to inspect the instance of AuthContext and read all its properties of type DbSet<T> as PropertyInfo[]. How can I cast the PropertyInfo to DbSet<T> in order to call the extension method on it ?

var currentContext = new AuthContext();
...
var dbSets = typeof(AuthContext).GetProperties(BindingFlags.Public | BindingFlags.Instance);
dbSets.Where(pi =>
                pi.PropertyType.IsGenericTypeDefinition &&
                pi.PropertyType.GetGenericTypeDefinition() == typeof(DbSet<>)).ToList()
      .ForEach(pi = ((DbSet<T>)pi.GetValue(currentContext, null)).Clear()); // !!!THIS WILL NOT WORK


推荐答案

Andras Zoltan的答案解释你做错了什么。

Please see Andras Zoltan's answer for an explanation of what you are doing wrong.

但是,如果您使用.NET 4.0,则不需要使用反射来调用该方法,您只需使用新的动态关键字:

However, if you use .NET 4.0, you don't need to use reflection to call the method, you can simply use the new dynamic keyword:

var currentContext = new AuthContext();
var dbSets = typeof(AuthContext).GetProperties(BindingFlags.Public | 
                                               BindingFlags.Instance);
dbSets.Where(pi => pi.PropertyType.IsGenericType &&
                   pi.PropertyType.GetGenericTypeDefinition() == typeof(DbSet<>))
      .ToList()
      .ForEach(pi => ExtensionClass.Clear((dynamic)pi.GetValue(currentContext, 
                                                               null)));

我从 DbSet< T> 动态并更改方法的调用方式。

因为清除方法,它不能直接在动态类型上调用,因为 dynamic 不知道扩展方法。但是由于扩展方法不只是静态方法,您可以随时将对扩展方法的调用更改为对静态方法的正常调用。

您所要做的一切都是更改 ExtensionClass 到定义 Clear 的实际类名。

I changed the cast from DbSet<T> to dynamic and changed the way the method is called.
Because Clear is an extension method, it can't be called directly on the dynamic type, because dynamic doesn't know about extension methods. But as extension methods are not much more than static methods, you can always change a call to an extension method to a normal call to the static method.
Everything you have to do is to change ExtensionClass to the real class name in which Clear is defined.

这篇关于将PropertyInfo转换为通用类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆