Paul.K
Paul.K

Reputation: 3

Call MethodInfo.Invoke on Method with genericArguments

I get an InvalidOperation Exception when calling MethodInfo.Invoke on my Method, its because it has generic Arguments. After hours of searching in Internet I don't know how to solve this problem. Here is the MethodInfo:

object value = null;
if (propertyType.IsClass)
{
    Type primaryKeyType = propertyType.GetPrimaryKeyType();
    object primaryKeyValue = property.Value.ToValue(primaryKeyType);
    MethodInfo GetEntityMethodInfo = typeof(ReportSettingsExtensions)
        .GetMethod("GetEntity", BindingFlags.Static | BindingFlags.InvokeMethod | BindingFlags.NonPublic);
    object entity = propertyType;
    GetEntityMethodInfo.Invoke(entity, new object[] { primaryKeyValue });
    value = entity.GetPrimaryKey();
}

And here is the method:

private static T GetEntity<T>(object primaryKeyValue)
{
    T entity = default(T);
    new Storage(storage =>
    {
        entity = storage.Create<T>();
        entity.SetPrimaryKey(primaryKeyValue);
        storage.Load(entity);
    });

    return entity;
}

Upvotes: 0

Views: 355

Answers (1)

Nick Butler
Nick Butler

Reputation: 24383

You need to provide or "close" the generic method parameter T, using MethodInfo.MakeGenericMethod ( MSDN )

Something like this:

MethodInfo getEntity =
  GetEntityMethodInfo.MakeGenericMethod( ... whatever T should be ... );

var entity = getEntity.Invoke( null, new object[] { primaryKeyValue } );

You should pass null as the first parameter to Invoke because the method is static and so doesn't have an object reference.

Upvotes: 2

Related Questions