按特定顺序自动运行功能

时间:2017-09-15 15:03:46

标签: c#

我想知道是否有办法在f.e中运行我的所有功能。 "功能 - 类"通过在我的main方法中放置一行。这背后的想法是,为了节省一些节奏和时间,写出每一个功能,并制作一个非常长的主要方法。

我正在考虑某事。喜欢(只是为了展示我正在寻找的东西):

namespace ConsoleApp1
{
    class Functions
    {
        public void Function1()
        {
            do.Something();
        }

    }
    class Program
    {
        static void Main(string[] args)
        {
            RunAllFunctionsInFunctionsInAlphabeticalOrder();
        }
    }
}

提前致谢!

2 个答案:

答案 0 :(得分:2)

尽管在这种情况下有关正确OOP的所有评论(我认为这些评论都是有效的),但这里有一个基于反思的例子:

    sw = New StreamWriter(fname, False)
    For i As Integer = 1 To 9
        Dim tb = DirectCast(t3frm.Controls("TextBoxLo" & i), TextBox)
        Dim cb = DirectCast(t3frm.Controls("comboboxlo" & i), ComboBox)
        sw.WriteLine(tb.Text)
        sw.WriteLine(Val(cb.SelectedIndex))
    Next

    For i As Integer = 1 To 3
        Dim tb = DirectCast(t3frm.Controls("textboxhi" & i), TextBox)
        Dim cb = DirectCast(t3frm.Controls("comboboxhi" & i), ComboBox)
        sw.WriteLine(tb.Text)
        sw.WriteLine(Val(cb.selectedindex))
    Next

    sw.Close()
    Me.Close()

这将有效地从类型class F { public void F1() { Console.WriteLine("Hello F1"); } } class MainClass { public static void Main(string[] args) { var f = new F(); foreach (var method in // get the Type object, that will allow you to browse methods, // properties etc. It's the main entry point for reflection f.GetType() // GetMethods allows you to get MethodInfo objects // You may choose which methods do you want - // private, public, static, etc. We use proper BindingFlags for that .GetMethods( // this flags says, that we don't want methods from "object" type, // only the ones that are declared here BindingFlags.DeclaredOnly // we want instance methods (use "Static" otherwise) | BindingFlags.Instance // only public methods (add "NonPublic" to get also private methods) | BindingFlags.Public) // lastly, order them by name .OrderBy(x => x.Name)) { //invoke the method on object "f", with no parameters (empty array) method.Invoke(f, new object[] { }); } } } 获取所有公共实例方法,按名称排序,并且不带参数执行。

在这种特殊情况下,它将显示:

  

你好F1

但总的来说,运行“所有方法”,更糟糕的是,依赖于它们的字母顺序,强烈建议不要这样做。

欢迎使用StackOverflow!

答案 1 :(得分:-2)

使用Func方法

        static void Main(string[] args)
        {

            List<Func<string, string>> methods = new List<Func< string, string>>(){
                methodA, methodB, methodC, methodD
            };

            foreach (Func<string,string> method in methods)
            {
                string result = method("a");

            }


        }
        static string methodA(string a)
        {
            return a;
        }
        static string methodB(string b)
        {
            return b;
        }
        static string methodC(string c)
        {
            return c;
        }
        static string methodD(string d)
        {
            return d;
        }