C# 将带字符串参数的操作传递给不带字符串参数的方法
我想把一个动作传递到一个方法中,并在那里用我在那里得到的参数filePath调用它。 如果我像下面这样做,则会使用我在ExportExecute的参数中传递的参数而不是filePath调用该方法C# 将带字符串参数的操作传递给不带字符串参数的方法,c#,methods,delegates,C#,Methods,Delegates,我想把一个动作传递到一个方法中,并在那里用我在那里得到的参数filePath调用它。 如果我像下面这样做,则会使用我在ExportExecute的参数中传递的参数而不是filePath调用该方法 ExportExecute(m => this.Method(null), "example") 导致 action.Invoke(null); 但我想要的是 action.Invoke(filePath); 我的代码: private void ExportExecu
ExportExecute(m => this.Method(null), "example")
导致
action.Invoke(null);
但我想要的是
action.Invoke(filePath);
我的代码:
private void ExportExecute(Action<string> action, string fileName)
{
var filePath = this.ExportDialog(fileName);
try
{
action.Invoke(filePath);
...
private void ExportExecute(操作,字符串文件名)
{
var filePath=this.ExportDialog(文件名);
尝试
{
action.Invoke(文件路径);
...
这不起作用,该操作使用null调用。通过正确的语法解决了我的问题 电话:
this.ExportExecute(this.MyMethod,“示例”)
调用this.Method(null)
时,提供给MyMethod
的参数是null
。但您实际需要的是提供x
的值:
this.ExportExecute(x => this.MyMethod(x), "Example")
或者更简单:
this.ExportExecute(this.MyMethod, "Example")
这实际上并没有改变代码。这将与问题中的代码完全相同,只是委托的名称不同。