簡體   English   中英

如何在C#中使用反射調用具有不同類型參數的方法

[英]How to call a method with arguments of different types using reflection in C#

我正在嘗試使用C#中的.NET反射調用一個帶有兩個參數(布爾值和字符串)的函數。 但是,使用以下代碼,我得到一個例外:

object[] paramList = new object[] { true, "Foo" };

Type wsType = typeof(MyWS);
MyWS inst = (MyWS)Activator.CreateInstance(wsType);
MethodInfo method = wsType.GetMethod(function);    // function = the name of the function to be called
method.Invoke(inst, paramList);

這將引發ArrayTypeMismatchException(“嘗試以與數組不兼容的類型訪問元素。”)。

似乎paramList導致了異常,但是我不知道為什么?

我嘗試調用的函數將類似於:

public bool EnableSchedule(bool enable, string password)
{
    ...
}

您的操作似乎沒有任何問題-除非問題出在“ MyWS”上。 我認為這堂課是公開的。 同時,嘗試向GetMethod()添加一些綁定標志,例如

wsType.GetMethod(function, BindingFlags.Static | BindingFlags.Public | BindingFlags.Instance);

暫無
暫無

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

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