使用Custom Class作为参数从MethodInfo调用方法

时间:2012-01-31 17:57:30

标签: c# reflection invoke methodinfo

我有这种情况: 一个具有某些属性的自定义类(Customer),如下所示:

public class Customer
{
    public int Handler { get; set; }
    public string Name { get; set; }
}

使用Method的一个自定义类,如下所示:

public class CustomerMethods
{
    public static void Insert(Customer customer)
    {
        //Do Something...
    }
}

因此,我将加载一个包含类名,属性名和属性值等信息的文本文件。 但是,真正的问题是,如何在设置Handler和Name属性的值后,从CustomerMethods类调用Insert方法并将Customer类作为参数传递?

哦,我几乎忘了,我正在努力避免条件限制,因为我有100多个班级。 / O \ 如果您需要更多信息,请告诉我PLZ ......

2 个答案:

答案 0 :(得分:2)

typeof(CustomerMethods).GetMethod(SomeName).Invoke(null, new Customer(...))

但是,如果可能的话,你应该尝试重构你的设计并避免这种情况。

答案 1 :(得分:1)

我只使用这些字符串来调用静态插入方法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 }
    );