本文介绍了有没有-动态函数指针,它根据字符串重新调用函数名称,从而重新调用函数名称.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们这样说:

CallFunction("FunctionName",arrParams);

//将按名称获取函数
公共FunctionName(object [] arrParams)
{

}

Lets say like this:

CallFunction("FunctionName", arrParams);

// Will get the function by name
Public FunctionName(object[] arrParams)
{

}

推荐答案

Type mytype = abc.GetType();
MethodInfo info = mytype.GetMethod("FunctionName");
info.Invoke(abc, params);




其中abc是其中具有功能FunctionName的实际对象. :rose:




Where abc is the actual object that has the function FunctionName in it. :rose:


// The class with the function.
public class MyClass
{

    // The function you want to call.
    public int FunctionName(int val1, int val2)
    {
        return val1 + val2;
    }

}

// A class that interacts with MyClass.
public class SomeOtherClass
{

    // Defines the method signature.
    private delegate int IntDelegate(int val1, int val2);

    // A variable to hold the function.
    private IntDelegate storedFunction = null;

    // Grabs a reference to the function and stores it for later use.
    public void StoreFunctionPointer(MyClass myInstance)
    {
        storedFunction = myInstance.FunctionName;
    }

    // Calls the stored function.
    public int CallStoredFunction(int val1, int val2)
    {
        return storedFunction(val1, val2);
    }

}


如果需要,可以将这些函数指针存储在字典中,以使用字符串键查找它们.


If you wanted, you could then store those function pointers in a dictionary to look them up using a string key.


这篇关于有没有-动态函数指针,它根据字符串重新调用函数名称,从而重新调用函数名称.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 18:24