尽管所有关于正确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!
没有什么内置的...它可以很容易地反映建(但要注意排除'Main'造成死循环!)。 – Richard
你是说你会有'Function1','Function2'和'Function3',并且你想要在没有明确地执行'Functions.Function1()'的情况下调用它们吗?这就是反思。然而,除非你有数百种方法,否则你最好明确地打电话给他们。如果你有数百种方法,你应该重新考虑你的整个方法。 – mason
学习OOP而不是询问如何订购你的功能 –