Home > Backend Development > C++ > How to Dynamically Invoke Methods with and without Parameters using Reflection in C#?

How to Dynamically Invoke Methods with and without Parameters using Reflection in C#?

Patricia Arquette
Release: 2025-01-18 02:41:12
Original
363 people have browsed it

How to Dynamically Invoke Methods with and without Parameters using Reflection in C#?

The following code example demonstrates how to dynamically call methods with and without parameters:

<code class="language-csharp">// Assembly1.dll
namespace TestAssembly
{
    public class MainClass
    {
        public void Execute(string parameter)
        {
            // 执行某些操作...
        }

        public void ExecuteWithoutParameters()
        {
            // 执行某些操作...
        }
    }
}

// 执行程序集 ExecutingAssembly.exe
public class ReflectionExample
{
    public void InvokeMethod(string methodName)
    {
        Assembly assembly = Assembly.LoadFile("...Assembly1.dll"); // 加载程序集

        Type type = assembly.GetType("TestAssembly.MainClass"); // 获取类型
        if (type != null)
        {
            MethodInfo methodInfo = type.GetMethod(methodName); // 获取方法信息
            if (methodInfo != null)
            {
                object result = null;
                ParameterInfo[] parameters = methodInfo.GetParameters(); // 获取参数信息
                object instance = Activator.CreateInstance(type); // 创建实例

                if (parameters.Length == 0)
                {
                    result = methodInfo.Invoke(instance, null); // 调用无参数方法
                }
                else
                {
                    object[] parameterValues = new object[] { "Hello" }; // 参数值
                    result = methodInfo.Invoke(instance, parameterValues); // 调用带参数方法
                }
            }
        }
    }
}</code>
Copy after login

The above is the detailed content of How to Dynamically Invoke Methods with and without Parameters using Reflection in C#?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template