C# 通过C中的方法返回并执行方法#
我有我的main类和MethodFinder类。我想通过MethodFinder获取要在Main中运行的方法名并执行它 我该怎么做 我想要的是一个类,它的方法返回Method1或Method2(基于某些条件),然后可以在main类的main方法中运行C# 通过C中的方法返回并执行方法#,c#,methods,return,action,C#,Methods,Return,Action,我有我的main类和MethodFinder类。我想通过MethodFinder获取要在Main中运行的方法名并执行它 我该怎么做 我想要的是一个类,它的方法返回Method1或Method2(基于某些条件),然后可以在main类的main方法中运行 public MainClass { public void Main() { var methodFinder = new MethodFinder(); var method = methodFi
public MainClass
{
public void Main()
{
var methodFinder = new MethodFinder();
var method = methodFinder.Find();
// Execute method
}
private void Method1(){}
private void Method2(){}
}
在这种情况下,只要方法具有相同的签名,就可以使用该类型。如果您的方法采用参数,则可以使用。如果它返回一个值,您可以使用
请注意,尽管此方法闻起来像是一种您可能希望使用来实现目标的情况,或者可能的情况。在这种情况下,您可以使用该类型,只要这些方法具有相同的签名。如果您的方法采用参数,则可以使用。如果它返回一个值,您可以使用
请注意,尽管这种方法闻起来像是一种情况,您可能希望使用它来实现您的目标,或者可能。您可以这样做,或者使用它来更具活力
public class MethodFinder
{
public delegate void MethodSignature();
//these can live whereever and even be passed in
private static void Method1() => Debug.WriteLine("Method1 executed");
private static void Method2() => Debug.WriteLine("Method2 executed");
//maintain an array of possibilities or soemthing.
//perhaps use reflection instead
private MethodSignature[] methods = new MethodSignature[] { Method1, Method2 };
public MethodSignature FindByName(string methodName)
=> (from m in methods
where m.Method.Name == methodName
select m).FirstOrDefault();
}
用法:
var methodFinder = new MethodFinder();
var method = methodFinder.FindByName("Method2");
method(); //output: "Method2 executed"
你可以这样做,或者用它来变得更有活力
public class MethodFinder
{
public delegate void MethodSignature();
//these can live whereever and even be passed in
private static void Method1() => Debug.WriteLine("Method1 executed");
private static void Method2() => Debug.WriteLine("Method2 executed");
//maintain an array of possibilities or soemthing.
//perhaps use reflection instead
private MethodSignature[] methods = new MethodSignature[] { Method1, Method2 };
public MethodSignature FindByName(string methodName)
=> (from m in methods
where m.Method.Name == methodName
select m).FirstOrDefault();
}
用法:
var methodFinder = new MethodFinder();
var method = methodFinder.FindByName("Method2");
method(); //output: "Method2 executed"
.Find()
返回的是什么?似乎是字符串
或MethodInfo
什么是MethodFinder
?它已经存在还是要实现?返回的是什么?似乎是字符串
或MethodInfo
什么是MethodFinder
?它是否已经存在,或者您想实现它?非常感谢Eric。没错,我也闻到了一个糟糕的设计!非常感谢你,埃里克。没错,我也闻到了一个糟糕的设计!谢谢,我也会试试这个。谢谢,我也会试试这个。