How to call a private common method in a C # transfer type at runtime

I tried the code below in .NET 3.5, but mi is null. How to call a private common method so that a type parameter can be passed at runtime? If SaveEntityGeneric is marked as open, this code works fine, but I do not want to publish it, because it is used only in another method of the same class to pass this class type using GetType ().

using System.Reflection; public class Main1 { static void Main() { new Class1().Test(); } } class Class1 { public void Test() { var mi = GetType().GetMethod("SaveEntityGeneric", BindingFlags.NonPublic); // why mi is null ? var gm = mi.MakeGenericMethod(GetType()); gm.Invoke(this, null); } void SaveEntityGeneric<TEntity>() { } } 
+4
source share
2 answers

Binding flags are complex to handle this. Use BindingFlags.NonPublic | BindingFlags.Instance BindingFlags.NonPublic | BindingFlags.Instance .

 var mi = GetType().GetMethod("SaveEntityGeneric", BindingFlags.NonPublic | BindingFlags.Instance); var gm = mi.MakeGenericMethod(GetType()); gm.Invoke(this, null); 
+6
source

Just make it internal, which will prevent this method from being used outside the assembly

0
source

All Articles