首頁 > 後端開發 > C++ > C#可以從字符串調用功能嗎?

C#可以從字符串調用功能嗎?

DDD
發布: 2025-01-26 02:09:08
原創
376 人瀏覽過

Can C# Call a Function from a String?

C#中透過字串呼叫函數

PHP 可以透過儲存在字串中的函數名稱來呼叫函數。例如:

<code class="language-php">$function_name = 'hello';
$function_name();

function hello() { echo 'hello'; }</code>
登入後複製

.NET 是否可以實現此功能?

可以。 可以使用反射來實現此功能。方法如下:

<code class="language-csharp">Type thisType = this.GetType();
MethodInfo theMethod = thisType.GetMethod(TheCommandString);
theMethod.Invoke(this, userParameters);</code>
登入後複製

請注意,被呼叫的方法必須具有公共存取修飾符。對於非公共方法,請使用 BindingFlags 參數:

<code class="language-csharp">Type thisType = this.GetType();
MethodInfo theMethod = thisType
    .GetMethod(TheCommandString, BindingFlags.NonPublic | BindingFlags.Instance);
theMethod.Invoke(this, userParameters);</code>
登入後複製

以上是C#可以從字符串調用功能嗎?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板