c# - 查找属于同一泛型类的所有属性

标签 c# generics

如果您不熟悉 Entity Framework ,它会生成一个如下所示的类

public partial class contextontext : DbContext
{
    public virtual DbSet<foo> foo { get; set; }
    public virtual DbSet<bar> bar { get; set; }
    //Etc, there could be lots of these DbSet properties
} 

我正在尝试构建一个类型列表 DbSet<T>集合,但我不确定如何检查泛型类型。我使用PropertyType.ToString().StartsWith("System.Data.Entity.DbSet`1")让它工作但这似乎是一种困惑且不必要的复杂方法。这是我用来获取属性的完整 LINQ。

foreach (var property in context.GetType().GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance).Where(p => p.PropertyType.ToString().StartsWith("System.Data.Entity.DbSet`1")))
{
   Type type = property.PropertyType.GenericTypeArguments[0];

   //other stuff...
}

我在属性对象中查找了一下,但没有找到任何线索。有一个Type在那里,但这始终是通用 DbSet 的特定于类型的实现(因为它应该是这样)。我如何检查它是否是通用集合,无论它是什么类型?

最佳答案

我认为你想要的只是:

var propertyType = property.PropertyType;

if (propertyType.IsGenericType
  && propertyType.GetGenericTypeDefinition() == typeof(DbSet<>))
{
  // ...
}

我现在看到你的 Where在你的代码的右边。那将是:

.Where(p => p.PropertyType.IsGenericType
  && p.PropertyType.GetGenericTypeDefinition() == typeof(DbSet<>))

method GetGenericTypeDefinition 从具体构造(“封闭”)泛型类型(例如 DbSet<foo> )到类型的定义(此处为 DbSet<TEntity> )。

关于c# - 查找属于同一泛型类的所有属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31416696/

相关文章:

c# - 由于缺少引用,无法将应用程序洞察支持添加到 azure webjob

c# - 使用 Microsoft 异步框架的基础知识

java - 未经检查的从通用 T 转换为可比较的阻止编译

C# 和泛型 : how can I handle processing based on type?

c# - 从 Razor (asp.net) 迁移到 Angular JS 作为模板引擎

c# - 是否可以在 ASP.NET 中保留页面之间的 View 状态?

c# - Xamarin Forms - 获取图像以填充包含网格列的宽度?

Java 泛型 : how to declare a generic parameter as the base type of another generic parameter?

java - 将字符串添加到列表 <Integer>

java - 删除 - 编译后的通用类型信息