我创建了一个通用方法:
private void UpdateAllProperties<idType, entityType>(entityType currentEntity, entityType newEntity)
where idType : IEquatable<idType>
where entityType : AbstractEntity<idType>
{
var currentEntityProperties = currentEntity.GetType().GetProperties();
var newEntityProperties = newEntity.GetType().GetProperties();
foreach (var currentEntityProperty in currentEntityProperties)
{
foreach (var newEntityProperty in newEntityProperties)
{
if (newEntityProperty.Name == currentEntityProperty.Name)
{
if (currentEntityProperty.PropertyType == typeof(AbstractEntity<>))
{
// Here i want to use this method again, but i need to inform the types.. how can i do anything like that:
var idPropertyType = currentEntityProperty.PropertyType.GetProperty("Id").GetType();
var entityPropertyType = currentEntityProperty.PropertyType;
// Here i got the error because i cannot set through this way
this.UpdateAllProperties<idPropertyType, entityPropertyType>(currentEntityProperty.GetValue(currentEntity, null), newEntityProperty.GetValue(newEntity, null));
break;
}
else if (currentEntityProperty.PropertyType == typeof(ICollection<>))
{
// TODO
break;
}
else
{
currentEntityProperty.SetValue(currentEntity, newEntityProperty.GetValue(newEntity, null), null);
break;
}
}
}
}
}
我该怎么做?
答案 0 :(得分:2)
在使用Type.GetMethod()
调用方法之前,您必须使用MethodInfo.MakeGenericMethod()
进行调用以获取方法并MethodInfo.Invoke()
使用正确的类型进行设置。
类似的东西:
var idPropertyType = currentEntityProperty.PropertyType.GetProperty("Id").PropertyType;
var entityPropertyType = currentEntityProperty.PropertyType;
var method = this.GetType().GetMethod("UpdateAllProperties",
BindingFlags.Instance | BindingFlags.NonPublic);
var genericMethod = method.MakeGenericMethod(idPropertyType, entityPropertyType);
genericMethod.Invoke(this, new[] {
currentEntityProperty.GetValue(currentEntity, null),
newEntityProperty.GetValue(newEntity, null)
});