2014-09-12 67 views
0

我目前必須使用具有公共屬性名稱的大類。子類中的細節是相同的(我無法改變類)。我不想將Amount類再次添加到不同的部分,而是希望使用泛型和反射來實例化它。泛型類型<T>激活器

我有以下代碼:

var amountProperty = value.GetType().GetProperty("Amount"); 
if (amountProperty != null && amountProperty.PropertyType.IsArray) 
{ 
    Type amountTypeArray = amountProperty.PropertyType; 
    Type amountType = amountProperty.PropertyType.GetElementType(); 

    var amountValue = amountProperty.GetValue(value); 
    if (amountValue == null) 
    { 
     amountValue = Activator.CreateInstance(amountTypeArray); 
    } 
    else 
    { 
     amountValue = IncrementArray<amountType>(amountValue); 
    } 
} 

第三屆最後一行amountValue = IncrementArray<amountType>(amountValue);amountType錯誤。如果我把它放在typeof(amountValue)也不起作用。 incrementArray方法是:

protected T[] IncrementArray<T>(T[] arrayIncrement) 
{ 
    var sectionCopy = arrayIncrement; 
    Array.Resize<T>(ref sectionCopy, arrayIncrement.Length + 1); 
    return sectionCopy; 
} 

我可能只是缺少一個真正簡單的解決方案。

+1

泛型和反射都沒有** **交到好朋友。它可以*完成*,但它是非常昂貴的...不是一個偉大的方法,國際海事組織。 – 2014-09-12 11:58:51

回答

1

您需要使用Reflection來調用IncrementArray<T>方法。

首先得到MethodInfo然後使用MakeGenericMethod

// Assuming incrementMethod is the MethodInfo of IncrementArray<T> 
incrementMethod.MakeGenericMethod(amountType).Invoke(amountValue);