我们可以用C#中的变量替换函数名吗

问题描述

我想检查是否可以从C#中的变量值创建函数名称。这是我正在尝试的。我有如下字符串列表:

' '

我的任务如下:

private List<string> _pages;
_pages.AddRange(new string[] { "Page1","Page2","Page3","Page4"});

对于列表中的每个字符串,我需要调用以下方法

private async void Sync_Page1() {}
private async void Sync_Page2() {}
private async void Sync_Page3() {}
private async void Sync_Page4() {}

尝试在Google上搜索,但未找到任何特定内容。因此不确定是否可以在C#中完成,但想知道是否有可能。

有什么想法吗?

解决方法

您可以将其映射到可以调用的字典项:

namespace ConsoleApp1
{
    class Program
    {
 
        public static void Main(String[] args)
        {
            PagesExecution pe = new PagesExecution();
            pe.Execute();
            Console.ReadLine();
        }
    }
 
    public class PagesExecution
    {
        //Action<string> a = new Action<string>();

        private List<string> _pages = new List<string>();
        private Dictionary<string,Action> dictionary = new Dictionary<string,Action>();
        public PagesExecution ()
        {
        }

        public void Execute()
        {               
            dictionary.Add("Page1",new Action(Sync_Page1));
            dictionary.Add("Page2",Sync_Page2);
            dictionary.Add("Page3",Sync_Page3);
            dictionary.Add("Page4",Sync_Page4);

           _pages.AddRange(new string[] { "Page1","Page2","Page3","Page4"});

            foreach (var entry in _pages)
            {
                dictionary[entry].Invoke();
            }
        }

        
        public void   Sync_Page1()
        {
            Console.WriteLine("Page1");
        }
        private void Sync_Page2()
        {
            Console.WriteLine("Page2");
        }
        private void Sync_Page3()
        {
            Console.WriteLine("Page3");
        }
        private void Sync_Page4()
        {
            Console.WriteLine("Page4");
        }

    }
}

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...