2017-09-15 36 views
-1

我想知道是否有方法可以在f.e中运行我所有的函数。通过在我的主要方法中放置一个特定的行来实现“功能 - 类”。这背后的想法是,为了节省一些时间和速度,写出每一个功能,并制定一个非常长的主要方法。以特定顺序自动运行功能

我正在考虑某事。 (只是为了证明我在找什么):

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

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

在此先感谢!

+2

没有什么内置的...它可以很容易地反映建(但要注意排除'Main'造成死循环!)。 – Richard

+0

你是说你会有'Function1','Function2'和'Function3',并且你想要在没有明确地执行'Functions.Function1()'的情况下调用它们吗?这就是反思。然而,除非你有数百种方法,否则你最好明确地打电话给他们。如果你有数百种方法,你应该重新考虑你的整个方法。 – mason

+7

学习OOP而不是询问如何订购你的功能 –

回答

2

尽管所有关于正确OOP在这种情况下的评论(我想这,是有效的),这里是一个小的基于反射的例子:

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[] { }); 
     } 
    } 
} 

这将,有效,让所有的公共实例方法从类型F,按名称排序,并执行不带参数。

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

你好F1

但总的来说运行“所有方法”,甚至更糟糕,取决于他们的字母顺序,是要强烈不鼓励。

欢迎来到StackOverflow!

+0

好吧,我不知道你在这里做什么,因为我对这个BindingFlags系统一无所知,它是如何工作的?你到底在做什么? –

+0

我会将代码分成几行并发表评论以提供帮助,但我也建议您使用https://msdn.microsoft.com/en-us/library/system.reflection.bindingflags(v=vs.110).aspx和https ://msdn.microsoft.com/en-us/library/4d848zkb(v = vs.110).aspx –

+0

再次感谢! –

-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; 
     } 
+0

Asker正在寻找动态解决方案 –

+0

OP在哪里寻求动态解决方案?你再一次做出错误的假设。 – jdweng

+0

当他说“节省一些步伐和时间,写出每一个功能,并制定一个非常长的主要方法” –