相关疑难解决方法(0)

检查类是否派生自泛型类

我的项目中有一个派生类的泛型类.

public class GenericClass<T> : GenericInterface<T>
{
}

public class Test : GenericClass<SomeType>
{
}
Run Code Online (Sandbox Code Playgroud)

有没有办法找出一个Type对象是否来自GenericClass

t.IsSubclassOf(typeof(GenericClass<>))
Run Code Online (Sandbox Code Playgroud)

不起作用.

c# generics reflection

287
推荐指数
11
解决办法
14万
查看次数

确定通用参数是否为Nullable类型

我有以下VB.NET函数,例如:

Public Function MyFunction (Of TData) (ByVal InParam As Integer) As TData

End Sub
Run Code Online (Sandbox Code Playgroud)

我如何在函数中确定是否TData为NULLable类型?

.net vb.net generics nullable

22
推荐指数
2
解决办法
6175
查看次数

如何通过反射加载所有Entity Framework 4.1实体配置实体?

在我的OnModelCreating数据上下文方法中,我目前手动映射所有实体配置映射类,如:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Configurations.Add(new UserMap());
    // 20 or so mapping configuration below
}
Run Code Online (Sandbox Code Playgroud)

我想通过使用反射来简化这一点,所以我有以下代码:

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        // Find all EntityTypeConfiguration classes in the assembly
        foreach (Assembly asm in AppDomain.CurrentDomain.GetAssemblies())
            foreach (Type t in asm.GetTypes())
                if (t.IsDerivedFromOpenGenericType(typeof(EntityTypeConfiguration<>)))
                    modelBuilder.Configurations.Add(Activator.CreateInstance(t));   
    }
Run Code Online (Sandbox Code Playgroud)

IsDerivedFromOpenGenericType是从这个问题,并正常工作.

问题是这不能编译,因为Activator.CreateInstance(t)返回一个object,但模型构建器期望a System.Data.Entity.ModelConfiguration.ComplexTypeConfiguration<TComplexType>.

通常在使用Activator类时我会将对象转换为我期望的类型t(或者我期望类采用的),但由于这是使用泛型,我不知道如何做到这一点.

有没有人有任何想法?

c# reflection entity-framework

4
推荐指数
2
解决办法
4051
查看次数

标签 统计

c# ×2

generics ×2

reflection ×2

.net ×1

entity-framework ×1

nullable ×1

vb.net ×1