Home >Backend Development >C++ >Can C# Invoke Functions Dynamically from Strings Using Reflection?

Can C# Invoke Functions Dynamically from Strings Using Reflection?

DDD
DDDOriginal
2025-01-26 02:21:08939browse

Can C# Invoke Functions Dynamically from Strings Using Reflection?

Calling functions through strings in C#

PHP can easily call functions through strings. So, can C# implement this function?

Answer: Reflection

Yes, reflection allows you to dynamically execute methods via strings. Here’s how:

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

This code works because it retrieves the method's MethodInfo using the string representation of the method name.

Non-public methods

If you need to call non-public methods, use BindingFlags:

<code class="language-csharp">MethodInfo theMethod = thisType
    .GetMethod(TheCommandString, BindingFlags.NonPublic | BindingFlags.Instance);
theMethod.Invoke(this, userParameters);</code>

This specifies that the method is non-public and instance-specific.

The above is the detailed content of Can C# Invoke Functions Dynamically from Strings Using Reflection?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn