没有反射的编译时通用类型映射

时间:2013-07-29 02:03:52

标签: c# nhibernate generics types repository-pattern

在C#中,有没有办法在编译期间将一个泛型类型映射到另一个泛型类型?我想避免使用Reflection来解决这个问题。例如,假设我想将TypeA映射到TypeB,并且具有类似于以下代码的工作:

private void List<U> GetItemList<T>() where T : class <== U is the destination type obtained by the compile-time mapping from T to U
{
    Type U = GetMappedType(typeof(T))   <=== this needs to happen during compile-time
    List<U> returnList = Session.QueryOver<U>().List();
    return returnList;
}

private Type GetMappedType(Type sourceType)
{
    if (sourceType == typeof(TypeA))
        return typeof(TypeB);
}

我意识到因为我正在使用方法调用来映射类型,所以它不会在编译期间进行映射,但是还有另一种方法可以实现我想要实现的目的,只是在编译期间吗?我知道上面的代码不正确,但我希望你能看到我想要的东西。

简而言之,我想知道是否有办法将一种类型映射到另一种类型,并让C#编译器知道类型映射,以便目标类型可以用作任何方法的通用类型参数采用通用类型参数。我想避免使用Reflection。

作为一个侧面问题,如果我确实使用了Reflection,它是否会使实现非常耗费资源?

1 个答案:

答案 0 :(得分:2)

是动态的答案。我最近遇到了同样的问题,我必须根据数据库中配置的某些值来切换存储库。

var tableNameWithoutSchema = tableName.Substring(tableName.IndexOf(".", StringComparison.Ordinal) + 1);
var tableType = string.Format("Library.Namespace.{0}, Library.Name", tableNameWithoutSchema);
var instance = UnitofWork.CreateRepository(tableType, uoW);

CreateRepository返回动态类型

public static dynamic CreateRepository(string targetType, DbContext context)
{
    Type genericType = typeof(Repository<>).MakeGenericType(Type.GetType(targetType));
    var instance = Activator.CreateInstance(genericType, new object[] { context });
    return instance;
}
需要上下文,因为我必须通过构造函数将上下文传递给Generic存储库。 在我的情况下,这种方法有一些问题。 可能这对你有帮助。