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;
}
我可能只是缺少一个真正简单的解决方案。
泛型和反射都没有** **交到好朋友。它可以*完成*,但它是非常昂贵的...不是一个伟大的方法,国际海事组织。 – 2014-09-12 11:58:51