我有几个方法都具有相同的参数类型和返回值,但名称和块不同。我想将要运行的方法的名称传递给另一个将调用传递的方法的方法。
public int Method1(string)
{
// Do something
return myInt;
}
public int Method2(string)
{
// Do something different
return myInt;
}
public bool RunTheMethod([Method Name passed in here] myMethodName)
{
// Do stuff
int i = myMethodName("My String");
// Do more stuff
return true;
}
public bool Test()
{
return RunTheMethod(Method1);
}
这段代码不起作用,但这就是我正在尝试做的。我不明白的是,由于我需要定义参数,因此如何编写 RunTheMethod 代码。
网友回答:
您需要使用委托。在这种情况下,所有方法都采用一个参数并返回一个 – 这最简单地由委托1 表示。因此,您的代码可以通过以下简单更改变得正确:string
int
Func<string, int>
public bool RunTheMethod(Func<string, int> myMethodName)
{
// ... do stuff
int i = myMethodName("My String");
// ... do more stuff
return true;
}
诚然,代表们拥有比这更大的权力。例如,使用 C#,您可以从 lambda 表达式创建委托,因此可以按以下方式调用方法:
RunTheMethod(x => x.Length);
这将创建一个匿名函数,如下所示:
// The <> in the name make it "unspeakable" - you can't refer to this method directly
// in your own code.
private static int <>_HiddenMethod_<>(string x)
{
return x.Length;
}
然后将该委托传递给该方法。RunTheMethod
您可以将委托用于事件订阅、异步执行、回调 – 各种事情。非常值得一读,特别是如果你想使用 LINQ。我有一篇文章主要是关于代表和事件之间的差异,但无论如何你都可能会发现它很有用。
1 这仅基于框架中的通用委托类型;您可以轻松声明自己的:Func<T, TResult>
public delegate int MyDelegateType(string value)
,然后改为将参数设置为类型。MyDelegateType
网友回答:
可以使用 .NET 3.5 中的委托作为方法中的参数。委托允许您指定一个方法,该方法采用特定类型的多个参数并返回特定类型的单个参数。下面是一个应该可以工作的示例:Func
RunTheMethod
Func
public class Class1
{
public int Method1(string input)
{
//... do something
return 0;
}
public int Method2(string input)
{
//... do something different
return 1;
}
public bool RunTheMethod(Func<string, int> myMethodName)
{
//... do stuff
int i = myMethodName("My String");
//... do more stuff
return true;
}
public bool Test()
{
return RunTheMethod(Method1);
}
}
网友回答:
从OP的例子来看:
public static int Method1(string mystring)
{
return 1;
}
public static int Method2(string mystring)
{
return 2;
}
您可以尝试操作委托!然后使用
public bool RunTheMethod(Action myMethodName)
{
myMethodName(); // note: the return value got discarded
return true;
}
RunTheMethod(() => Method1("MyString1"));
或
public static object InvokeMethod(Delegate method, params object[] args)
{
return method.DynamicInvoke(args);
}
然后简单地调用方法
Console.WriteLine(InvokeMethod(new Func<string,int>(Method1), "MyString1"));
Console.WriteLine(InvokeMethod(new Func<string, int>(Method2), "MyString2"));
模板简介:该模板名称为【如何使用 C# 将方法作为参数传递?】,大小是暂无信息,文档格式为.编程语言,推荐使用Sublime/Dreamweaver/HBuilder打开,作品中的图片,文字等数据均可修改,图片请在作品中选中图片替换即可,文字修改直接点击文字修改即可,您也可以新增或修改作品中的内容,该模板来自用户分享,如有侵权行为请联系网站客服处理。欢迎来懒人模板【C#】栏目查找您需要的精美模板。