铸造仿制药

时间:2014-10-15 08:08:02

标签: c# generics

我正在尝试将DbSet<BaseContact>投射到DbSet<TEntity>。我的问题如下所示,我正在尝试输入Contact并将其转换为DbSet<BaseContact>,但我只能返回DbSet类型DbSet<TEntity>BaseContactContact的超类。

我怎么能做这个演员?有什么建议吗?

//Input: Set<Contact> -> Output: DbSet<BaseContact>
public DbSet<TEntity> Set<TEntity>()
    where TEntity : class, IObjectState
{
    Return DBSet<BaseContact> as DBSet<TEntity>;
}

PS:使它不通用是没有选择的,因为我正在通过它运行其他类型。上面的代码不是整个函数。

这是完整的功能:

public DbSet<TEntity> Set<TEntity>()
            where TEntity : class, IObjectState
{
    var propertyInfos = GetType().GetProperties(BindingFlags.Instance | BindingFlags.NonPublic);

    foreach (PropertyInfo property in propertyInfos)
    {
        if (property.PropertyType == typeof(FakeDbSet<TEntity>))
            return property.GetValue(this, null) as FakeDbSet<TEntity>;
    }

    var baseType = typeof(TEntity).BaseType;

    while( typeof(object) != baseType )
    {
        foreach(var property in propertyInfos)
        {
            if(property.PropertyType == typeof(FakeDbSet<>).MakeGenericType(baseType))
            {
                var baseTypeDbSet = property.GetValue(this, null);
                // you will need to convert FakeDbSet<TBaseType> to FakeDbSet<TEntity>
                var entityDbSet = Convert.ChangeType(baseTypeDbSet, typeof(FakeDbSet<>).MakeGenericType(baseType)) as FakeDbSet<TEntity>;
                return entityDbSet;
            }
        }
        baseType = baseType.BaseType;
    }

    throw new Exception("Type collection not found");
}

0 个答案:

没有答案
相关问题