C # Dynamic Method Calling Common Functions

I have the following two functions:

public class MyClass { public void Save<TObject>(TObject object) where TObject : class { } public void Save<TObject>(TObject object, String strValue) where TObject : class { } } 

I want to be able to dynamically call the first save function, similar to the following:

 public void DoSomething<T>(String strMethod) where T : class { T myObject = Activator.CreateInstance<T>(); MyClass.GetType().GetMethod(strMethod, new Type[] { typeof(T) }).MakeGenericMethod(typeof(T)).Invoke(null, new[] { myObject }); } 

Unfortunately, when I do this, it cannot match the first save function. If I remove new Type[] { typeof(T) } , I am stuck with the ambiguity problem. What am I missing?

+4
source share
2 answers

Generic type arguments will not match; the specific T in DoSomething does not match the public TObject parameter . Instead, find all the Save methods, and then filter after that:

 ...GetMethods().Single(m => m.Name == strMethod && m.GetParameters().Length == 1)... 
+2
source

I'm not sure if this will fix your problem, but you have to call Invoke () on the MyClass instance, you don't know why you are calling it with a null value.

+1
source

Source: https://habr.com/ru/post/1391736/


All Articles