2013-01-04 124 views
0

我得到一個InvalidOperation異常時,我的方法,因爲它有通用的參數調用MethodInfo.Invoke。在互聯網搜索幾個小時後,我不知道如何解決這個問題。這裏是MethodInfo調用MethodInfo.Invoke方法與泛型參數

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

這裏是方法:

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

我曾問過類似的問題,並得到了很好的回答: http://stackoverflow.com/questions/6333896/invoking-a-method-via-reflection-with-generics-and-overrides – Pete

回答

2

您需要提供或 「關閉」 的泛型方法參數T,使用MethodInfo.MakeGenericMethodMSDN

喜歡的東西這個:

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

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

您應該將null作爲第一個參數傳遞給Invoke,因爲方法是static,因此沒有對象引用。

+0

它仍然犯規完全工作,但這個答案幫了很多,謝謝! –