Invoke Method from MethodInfo with Custom Class as Parameter
-
21-04-2021 - |
سؤال
I have this scenario: One custom class (Customer) with some properties, like this:
public class Customer
{
public int Handler { get; set; }
public string Name { get; set; }
}
One custom class with the Method, like this:
public class CustomerMethods
{
public static void Insert(Customer customer)
{
//Do Something...
}
}
So, I will load a text file with some info, like class name, property name and property value. But, the real problem is, how can I invoke the Insert Method from CustomerMethods class and pass Customer class as parameter after set the values of Handler and Name properties?
Oh, I almost forget, I am trying to avoid conditionals, because I have 100+ classes. /o\ Ty all, if you need more info, just tell me plz...
المحلول
I used only these strings to call static Insert method WindowsFormsApplication1.Form1+CustomerMethods
WindowsFormsApplication1.Form1+Customer
Insert
Type customerMethodsType = Type.GetType("WindowsFormsApplication1.Form1+CustomerMethods");
Type customerType = Type.GetType("WindowsFormsApplication1.Form1+Customer");
object customerObject = Activator.CreateInstance(customerType);
customerType.GetProperty("Handler").SetValue(customerObject, 3, null);
customerMethodsType.InvokeMember(
"Insert",
BindingFlags.Public | BindingFlags.InvokeMethod| BindingFlags.Static,
null,
null,
new object[] { customerObject }
);
نصائح أخرى
typeof(CustomerMethods).GetMethod(SomeName).Invoke(null, new Customer(...))
However, you should try to refactor your design and avoid this, if possible.