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

Can C# Invoke Functions Dynamically from Strings Using Reflection?

DDD
Release: 2025-01-26 02:21:08
Original
969 people have browsed it

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:

Type thisType = this.GetType();
MethodInfo theMethod = thisType.GetMethod(TheCommandString);
theMethod.Invoke(this, userParameters);
Copy after login

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:

MethodInfo theMethod = thisType
    .GetMethod(TheCommandString, BindingFlags.NonPublic | BindingFlags.Instance);
theMethod.Invoke(this, userParameters);
Copy after login

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 of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template