2012-12-14 18 views
0

可能重複:
Pass Type dynamically to <T>如何動態地在一個類型傳遞的<T>

我怎麼會做類似下面的? historyType在Adapt中不是公認的類型。

Type historyType = Type.GetType("Domain.MainBoundedContext.CALMModule.Aggregates.LocationAgg." + modifiedEntry.GetType().Name + "History"); 

ServiceLocationHistory history = adapter.Adapt<ServiceLocation, historyType>(modifiedEntry as ServiceLocation); 
historyRepository.Add(history); 

編輯: 我落得這樣做:

ServiceLocationHistory history = adapter.GetType() 
            .GetMethod("Adapt", new Type[] { typeof(ServiceLocation) }) 
            .MakeGenericMethod(typeof(ServiceLocation), typeof(ServiceLocationHistory)) 
            .Invoke(adapter, new object[] { modifiedEntry as ServiceLocation }) 
            as ServiceLocationHistory; 
+0

注意,重複的問題,同時包含「爲什麼你不應該這樣做」,以及「如何做到這一點,如果我需要」由馬克Gravell。 –

回答

2

這可能是也可能不是一個選擇,但你可以隨時使用DynamicMethod的,放出IL創建你的類型,並返回一個ServiceLocationHistory。我經常這樣做而不是哈克反射技巧,而且它幾乎總是更快。

否則,反思你可以這樣做:

ServiceLocationHistory history = adapter.GetType() 
             .GetMethod("Adapt") 
             .MakeGenericMethod(typeof(ServiceLocation), historyType) 
             .Invoke(adapter, new [] {modifiedEntry}) 
             as ServiceLocationHistory; 
相關問題