[英]C#, Generics, Type and NHibernate
我正在與NHibernate一起學習C#中泛型的功能。 我想在粘貼的代碼中嘗試以下操作。
為了對N個NHibernate對象進行一些后期處理,我嘗試了一種利用泛型的實用程序方法,使其適用於我們現在或將來使用的所有NHibernate映射類。 它可以工作,但是我需要對每個映射類的每個調用進行硬編碼。 這是一個痛苦,隨着我們的架構和映射會隨着時間的推移而不斷變化,需要不斷進行更新。
我確實通過動態生成的NHibernate映射按字符串名稱提供了所有映射類的最新列表。 如果有一種方法可以使用此字符串名稱列表來調用基於泛型的方法,我會非常高興。
誰能告訴我這是否可能? 我需要尋找其他路線嗎?
提前非常感謝!!!
public static void ProcessSomeItems()
{
// *************************************************************
// As of now I have to list all classes as such to be processed
// It works but I have to update manually when new mapping classes are created
// *************************************************************
NHibDoSomethingUtil<AspnetMembership>();
NHibDoSomethingUtil<AspnetProfile>();
NHibDoSomethingUtil<AspnetRole>();
NHibDoSomethingUtil<AspnetUser>();
// and so forth...
// I have a up-to-date list of all mappings from "HbmMapping" and can get a list of all in the
// list form as below
List<string> mappingNames = new List<string>();
foreach (string mappingName in mappingNames)
{
Type theType = Type.GetType(mappingName);
// I know I'm getting Types and Generics classes and so forth all jumbled but
// how in the heck would I do something like the below?
NHibDoSomethingUtil<theType>(); // Obviously doesn't compile ;-)
}
}
// Generic method
public static void NHibDoSomethingUtil<T>() where T : class
{
using (ISession session = sourceDBSessionFactory.OpenSession())
{
foreach (dynamic item in new List<T>(session.QueryOver<T>().List()))
{
// Process item;
}
}
}
ecsousa做出了很大的貢獻,我能夠用下面的東西來完成我所需要的。
foreach (HbmClass mappingClass in mapping.Items)
{
Console.WriteLine(" -- Discovered Mapping: " + mappingClass.Name);
Type mappingClassType = Type.GetType(mappingClass.Name);
var genericMethod = typeof(Migration).GetMethod("NHibDoSomethingUtil");
var method = genericMethod.MakeGenericMethod(mappingClassType);
method.Invoke(null, null);
}
您將需要使用反射來完成此操作。 代替直接調用NHibDoSomethingUtil,請嘗試以下操作:
var genericMethod = typeof(TheClassName).GetMethod("NHibDoSomethingUtil");
var method = genericMethod.MakeGenericMethod(theType);
method.Invoke(null, null);
請注意,您必須用包含兩個方法的類替換TheClassName
。
請記住,這種代碼很慢,您應該非常小心地使用它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.