我已經有點難以解決如何將數據對象傳遞給它的處理器類。我試圖給出一個下面的問題的簡單例子。我試圖找出是否有一種類型安全的方式來實例化使用通用接口的處理器?創建通用接口實例時可以動態指定類型嗎?
乾杯,
查理
class APieceOfState
{
public string AbitOfData { get; set; }
}
interface IDescribeSomething<in T>
{
void Process(T type) ;
}
class ImplementWhatIsDescribed : IDescribeSomething<APieceOfState>
{
public void Process(APieceOfState type)
{
Console.WriteLine("Processing {0}", type.GetType());
}
}
private static void Main(string[] args)
{
var nextTest = new ImplementWhatIsDescribed();
var newStateObj = new APieceOfState();
nextTest.Process(newStateObj);
// Map processor to data in a dictionary
var dic = new Dictionary<Type, Type>();
var task = new APieceOfState();
var taskProcessor = new ImplementWhatIsDescribed();
dic.Add(task.GetType(), taskProcessor.GetType());
// Lookup processor using data type
Type lookupProcessorType;
dic.TryGetValue(task.GetType(), out lookupProcessorType);
// vvvvvvvvvvv - How can I make this dynamic based on task.GetType() ?
var instance = (IDescribeSomething<APieceOfState>)Activator.CreateInstance(lookupProcessorType);
instance.Process(task);
Console.ReadKey();
}