C# 泛型类型<;T>;带活化剂
我目前必须使用一个具有公共属性名的大型类。子类中的详细信息是相同的(我无法更改类)。我希望使用泛型和反射来实例化Amount类,而不是将Amount类重新添加到不同的部分 我有以下代码:C# 泛型类型<;T>;带活化剂,c#,generics,C#,Generics,我目前必须使用一个具有公共属性名的大型类。子类中的详细信息是相同的(我无法更改类)。我希望使用泛型和反射来实例化Amount类,而不是将Amount类重新添加到不同的部分 我有以下代码: var amountProperty = value.GetType().GetProperty("Amount"); if (amountProperty != null && amountProperty.PropertyType.IsArray) { Type amountType
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);
}
}
我可能只是缺少了一个真正简单的解决方案。您需要使用
反射
来调用增量数组
方法
首先获取MethodInfo
,然后使用MakeGenericMethod
// Assuming incrementMethod is the MethodInfo of IncrementArray<T>
incrementMethod.MakeGenericMethod(amountType).Invoke(amountValue);
//假设incrementMethod是IncrementArray的MethodInfo
incrementMethod.MakeGenericMethod(amountType).Invoke(amountValue);
泛型和反射不能成为好朋友。这是可以做到的,但它是非常昂贵的。。。这不是个好办法,国际海事组织。
// Assuming incrementMethod is the MethodInfo of IncrementArray<T>
incrementMethod.MakeGenericMethod(amountType).Invoke(amountValue);