C# 无反射的编译时泛型类型映射

C# 无反射的编译时泛型类型映射,c#,nhibernate,generics,types,repository-pattern,C#,Nhibernate,Generics,Types,Repository Pattern,在C#中,有没有办法在编译时将一个泛型类型映射到另一个泛型类型?我想避免在这个问题上使用反思。例如,假设我希望将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 =

在C#中,有没有办法在编译时将一个泛型类型映射到另一个泛型类型?我想避免在这个问题上使用反思。例如,假设我希望将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);
}

private void List GetItemList(),其中T:classYes dynamic将是答案。最近我遇到了同样的问题,我不得不根据数据库中配置的一些值切换存储库

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;
}
publicstaticdynamiccreaterepository(字符串targetType,DbContext上下文)
{
Type genericType=typeof(Repository).MakeGenericType(Type.GetType(targetType));
var instance=Activator.CreateInstance(genericType,新对象[]{context});
返回实例;
}
上下文是必需的,因为我必须通过构造函数将上下文传递给通用存储库。 在我的例子中,这种方法有一些问题。
这可能会对您有所帮助。

您想用它实现什么目标?@dmay我正在为我的应用程序构建一个存储库层:[域层存储库层(w/NHibernate类型)DB]。我想要一个函数,它接受域类型和Func,并输出与该函数匹配的域类型列表。问题是,使用NHibernate,我无法使用传入域类型进行查询,我必须使用相应的存储库类型进行查询。我有一个将我的域类型映射到NHibernate类型的函数。因此,我必须首先将我的域类型转换为NHibernate类型,然后使用生成的NH类型查询NHibernate。(contd…(…contd)所以本质上我必须使用动态类型作为泛型类型参数。我想我可能已经找到了解决办法,那就是使用C#4.0中引入的“dynamic”关键字。它允许编译器基本上绕过对象的类型安全性(据我所知),因为您可以在动态确定对象类型的任何地方使用它。不过,我仍在测试它,所以一旦我确定答案,我会在这里发布答案。如果你不介意我问的话,你对这种方法有什么问题?因为我想我走的是同一条路..问题是我必须使用lambda来过滤一些记录,但是你不能将lambda用于动态对象。你不能将动态转换为你的类型并使用lambda吗?