2

I have a foreach loop running on a list of types. Passing in a variable of type Type as a Type fails outright. Based on similar questions seen on this site, I wrote up a reflection-powered solution but this fails at runtime. I do not know how to proceed from this point.

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);
}
LoonyLadle
  • 23
  • 3
  • Possible duplicate of [How do I use reflection to call a generic method?](https://stackoverflow.com/questions/232535/how-do-i-use-reflection-to-call-a-generic-method) – just-my-name Aug 04 '19 at 05:37
  • @just-my-name: the problem is that they are trying to call a generic method, even though the method is _not_ in fact generic. See my answer below. – Peter Duniho Aug 04 '19 at 05:39
  • @PeterDuniho I see, the type itself is generic, thanks for pointing that out. – just-my-name Aug 04 '19 at 05:40

1 Answers1

2

In this statement:

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

You are trying to make a generic method. But the thing that's generic is the type, not the method. You should be calling Type.MakeGenericType() instead:

typeof(DefDatabase<>).MakeGenericType(defType).GetMethod("ResolveAllReferences",
    BindingFlags.Public | BindingFlags.Static).Invoke(null, null);
Peter Duniho
  • 68,759
  • 7
  • 102
  • 136