Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/332.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何从数据结构调用函数?_C# - Fatal编程技术网

C# 如何从数据结构调用函数?

C# 如何从数据结构调用函数?,c#,C#,我希望能够将一些操作描述为数据结构中表示的函数调用。然后我希望能够遍历数据结构并调用函数 此伪代码描述了我想要实现的目标: static void Main(string[] args) { Action[] actions = new Action[] { new Action(DoAction1(5)), new Action(DoAction1(7)), new Action(DoAction2("100201")),

我希望能够将一些操作描述为数据结构中表示的函数调用。然后我希望能够遍历数据结构并调用函数

此伪代码描述了我想要实现的目标:

static void Main(string[] args)
{
    Action[] actions = new Action[]
    {
        new Action(DoAction1(5)),
        new Action(DoAction1(7)),
        new Action(DoAction2("100201")),
    };

    foreach (Action action in actions)
    {
        action.<Run the action function>;
    }
}

public static void DoAction1(int x)
{
}

public static void DoAction2(string x)
{
}
它看起来有点像代表,但不完全像


关于如何实现这一点,你有什么想法吗?

这就是你想要的

Action[] actions = new Action[]
{
    new Action(()=>DoAction1(5)),
    new Action(()=>DoAction1(7)),
    new Action(()=>DoAction2("100201"))
};

foreach (Action action in actions)
{
    action();
}

也许你可以使用反射

var methodNames = typeof(MyType).GetMethods(BindingFlags.Public |
                                            BindingFlags.Static)
                                .Select(x => x.Name)
                                .Distinct()
                                .OrderBy(x => x);

因为您似乎不想使用Action类,所以可以查看代码库,特别是SharpByte.Dynamic命名空间。它允许只需一个方法调用即可评估语句和执行脚本,如下所示:

someContextObject.Execute("[executable code here]");
然而,你可以用另一种方式,这可能是你正在寻找的。当您执行其中一个动态编译/执行扩展方法时,解释如下:

IExecutable executable = ExecutableFactory.Default.GetExecutable(ExecutableType.Script, "[source code here]", optionalListOfParameterNames, optionalListOfNamespaces);

如果您想计算表达式/函数而不是运行多行语句,那么可以使用ExecutableType.expression。主要的一点是,您可以保留对对象的引用,并根据需要多次运行它,每次传递不同的参数值。您还可以使用各自的.copy方法自由复制IExecutable对象;它们被设计成线程安全但轻量级的,因此可以将引用或副本放在数据结构中以供进一步重用。解释得更多。

net中的Action类允许您直接分配lambda

var actions = new List<Action>
{
    () => DoAction1(5),
    () => DoAction1(7),
    () => DoAction2("100201"),
};
然后,您可以向列表中添加更多操作

actions.Add(() => DoAction2("blah blah"));

喜欢我不明白你的意思。结果应该是执行DoAction15,然后执行DoAction17和DoAction2100201。但是,它不应该硬编码。我想用数据结构来表示它,我不明白用数据结构来表示它对你来说是什么样子;你把它们排成一列;这是一个数据结构…看起来很有希望。动作类会如何支持这一点?很抱歉我的困惑。我没有意识到Action类是在.NET中定义的。我只是突然选了那个班的名字。我删除了我自己的动作类声明,它工作得非常好!除此之外,我唯一希望的是能够将其干净地序列化为JSON并返回,但这似乎不可能。看起来这只是将某个.NET对象作为数据进行检查,以便操作该数据。看起来我无法调用定义为数据的函数。
actions.ForEach(a => a());
actions.Add(() => DoAction2("blah blah"));