簡體   English   中英

使用自定義類作為參數從MethodInfo調用方法

[英]Invoke Method from MethodInfo with Custom Class as Parameter

我有這種情況:一個具有某些屬性的自定義類(客戶),如下所示:

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 \\全部,如果您需要更多信息,請告訴我...

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

但是,您應該嘗試重構您的設計,並盡可能避免這種情況。

我僅使用這些字符串來調用靜態插入方法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 }
    );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM