MST

星途 面试题库

面试题:C#中如何利用反射动态创建对象并调用其方法

假设有一个类`Calculator`,包含一个公共方法`Add(int a, int b)`用于返回两数之和。请通过反射动态创建`Calculator`类的实例,并调用`Add`方法,传入参数3和5,最后输出结果。
27.8万 热度难度
编程语言C#

知识考点

AI 面试

面试题答案

一键面试

以下是使用C#实现的代码示例:

using System;
using System.Reflection;

class Program
{
    static void Main()
    {
        // 获取Calculator类所在的程序集
        Assembly assembly = Assembly.GetExecutingAssembly();
        // 获取Calculator类的类型
        Type calculatorType = assembly.GetType("Calculator");
        // 通过反射创建Calculator类的实例
        object calculatorInstance = Activator.CreateInstance(calculatorType);
        // 获取Add方法
        MethodInfo addMethod = calculatorType.GetMethod("Add");
        // 调用Add方法并传入参数3和5
        object result = addMethod.Invoke(calculatorInstance, new object[] { 3, 5 });
        // 输出结果
        Console.WriteLine(result);
    }
}

class Calculator
{
    public int Add(int a, int b)
    {
        return a + b;
    }
}

以下是使用Java实现的代码示例:

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Main {
    public static void main(String[] args) {
        try {
            // 获取Calculator类的Class对象
            Class<?> calculatorClass = Class.forName("Calculator");
            // 通过反射获取Calculator类的构造函数并创建实例
            Constructor<?> constructor = calculatorClass.getConstructor();
            Object calculatorInstance = constructor.newInstance();
            // 获取Add方法
            Method addMethod = calculatorClass.getMethod("Add", int.class, int.class);
            // 调用Add方法并传入参数3和5
            Object result = addMethod.invoke(calculatorInstance, 3, 5);
            // 输出结果
            System.out.println(result);
        } catch (ClassNotFoundException | NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}

class Calculator {
    public int Add(int a, int b) {
        return a + b;
    }
}

请注意,上述C#代码中的Calculator类需和Program类在同一程序集中,Java代码中的Calculator类需和Main类在同一包下且包名匹配Class.forName中的类名全限定名。如果实际情况不同,需相应调整获取类型和创建实例的逻辑。