将PropertyInfo转换为通用类型

编程入门 行业动态 更新时间:2024-10-28 10:21:51
本文介绍了将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转换为通用类型

本文发布于:2023-11-03 07:01:33,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1554512.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换为   类型   PropertyInfo

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!