我有一个在类型列表上运行的foreach循环。将Type类型的变量作为Type传递完全失败。基于在此站点上看到的类似问题,我编写了一种基于反射的解决方案,但是在运行时失败了。从这一点上我不知道该如何进行。

foreach (Type defType in GenDefDatabase.AllDefTypesWithDatabases())
{
    // Compile Error: 'defType' is a variable but is used like a type
    DefDatabase<defType>.ResolveAllReferences();
    // Runtime Error: System.ArgumentException: The method has 0 generic parameter(s) but 1 generic argument(s) were provided.
    //   at System.Reflection.MonoMethod.MakeGenericMethod (System.Type[] methodInstantiation) [0x00000] in <filename unknown>:0
    typeof(DefDatabase<>).GetMethod("ResolveAllReferences", BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(defType).Invoke(null, null);
}

最佳答案

在此语句中:

typeof(DefDatabase<>).GetMethod("ResolveAllReferences",
    BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(defType).Invoke(null, null);


您正在尝试制作通用方法。但是通用的是类型,而不是方法。您应该改为呼叫Type.MakeGenericType()

typeof(DefDatabase<>).MakeGenericType(defType).GetMethod("ResolveAllReferences",
    BindingFlags.Public | BindingFlags.Static).Invoke(null, null);

09-28 04:10