C# 利用类名字符串调用并执行类方法

/// <summary>
/// 调用并执行指定类里面的函数
/// </summary>
/// <param name="className">需要调用的类名(包含其命名空间)</param>
/// <param name="methodName">需要调用的方法名</param>
public void GetAndExecuteMethod(string className, string methodName)
{
    try
    {
        var type = Type.GetType(className);
        if (type == null)
            throw new NullReferenceException("类" + className + "不存在");

        var obj = type.Assembly.CreateInstance(className);
        //调用其方法
        var method = type.GetMethod(methodName);
        if(method == null)
            throw new NullReferenceException("方法" + methodName + "不存在");

        //执行方法
        method.Invoke(obj, null);
    }
    catch (Exception)
    {
        throw;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章