如何在使用泛型方法时设置泛型属性?

时间:2012-03-01 13:39:58

标签: c# generics reflection

我创建了一个通用方法:

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;
                }
            }
        }
    }
}

我该怎么做?

1 个答案:

答案 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)
});