有没有-动态函数指针,它根据字符串重新调用函数名称,从而重新调用函数名称. [英] Is there any - dynamic function pointer, which calls a function acording to string represeting the function name.

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

问题描述

让我们这样说:

CallFunction("FunctionName",arrParams);

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

}

Lets say like this:

CallFunction("FunctionName", arrParams);

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

}

推荐答案

是的,为什么不呢?
使用反射.

Yes, why not.
Use Reflection.

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 previous answer is correct. Just thought I''d add that you can also create a delegate to store a "pointer" to a function. You can pass that around just like any other variable. Here is an example:
// 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.


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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆