如何在C#中从特殊函数(仅使用其字符串名称)中调用类中的其他函数? [英] How Can i call other functions in a class from special function(Just with their string names) in C#?

查看:163
本文介绍了如何在C#中从特殊函数(仅使用其字符串名称)中调用类中的其他函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名称为GoldClass的班级.它有四个名称分别为F()S()TH()Fo()的方法.在方法FO()中.我想调用其他三个方法(F,S,TH),但是只使用它们的名称.

I have a Class by name of GoldClass. It has four methods by names F(),S(),TH(),Fo(). In the methods FO(). I want to call three other methods (F,S,TH) but just use their names like this.

public void Fo()
{
    list <string> FuncsList=new list<string>();
    FuncsList.Add("F");
    FuncsList.Add("S");
    FuncsList.Add("TH");

    //NOW I WANT TO CALL THEM BUT USE MY STRINGS IN MY FUNCSLIST  
}

我最初使用了Reflection ...,但是我为班级中的公共变量分配了一些值.当反射成为新实例时,我所有在公共变量中的数据都丢失了.

I used Reflection at first ... but I am assigning some values to public variables in my class..and when reflection make new instance all my data in public variables is lost.

推荐答案

是否有任何特殊原因,您需要将它们存储为字符串.如果它们都是同一类中的无参数void方法,则可以将它们存储为Action s

Is there any particular reason, you need to store them as strings. If they're all parameterless void methods in the same class, you could store them as Actions

void Main()
{
    A();
}

public void A()
{
    List<Action> list = new List<Action>();
    list.Add(B);
    list.Add(C);
    list.Add(D);

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


public void B()
{
    Console.WriteLine("B Called");
}


public void C()
{
    Console.WriteLine("C Called");
}


public void D()
{
    Console.WriteLine("D Called");
}

话虽如此,但根本不清楚为什么需要这样做.为什么需要动态执行此操作.以下内容是否足够?

Having said that, It's not at all clear why you need to do this at all. Why do you need to do this dynamically. would the following not suffice.

public void FO()
{
    F();
    S();
    TH();
}

这篇关于如何在C#中从特殊函数(仅使用其字符串名称)中调用类中的其他函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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