[英]C# pass parameter to delegate
Hello I have a little problem with C# syntax... 您好,我在使用C#语法时遇到了一些问题...
Right now I'm passing four parameters to a method called WriteConfig
现在,我将四个参数传递给称为
WriteConfig
的方法
var task = fac.StartNew(() => { vault.WriteConfig(fileName, id, queue, DeleteUploadQueue); });
DeleteUploadQueue
is a delegate and gets called with id
as parameter inside WriteConfig
. DeleteUploadQueue
是一个委托,在WriteConfig
以id
作为参数进行调用。 What I want to do is pass id
to DeleteUploadQueue
outside instead of inside WriteConfig
so that I dont have to pass id
to WriteConfig
. 我想要做的就是通过
id
来DeleteUploadQueue
而不是外内WriteConfig
让我不必通过id
来WriteConfig
。
WriteConfig
looks like this: WriteConfig
看起来像这样:
public void WriteConfig(string fileName, int id, BlockingCollection<byte[]> queue, Action<int> deleteFunc)
But I cannot come up with the correct syntax for this. 但是我无法为此提供正确的语法。
Thank you for your help 谢谢您的帮助
Assuming you change the signature to this: 假设您将签名更改为此:
public void WriteConfig(string fileName, BlockingCollection<byte[]> queue, Action deleteFunc)
You could write 你可以写
var task = fac.StartNew(() => { vault.WriteConfig(fileName, queue, ()=> DeleteUploadQueue(id)); });
sounds like you want 听起来像你想要的
var task = fac.StartNew(() => { vault.WriteConfig(fileName, id, queue,
() => DeleteUploadQueue(id)); })
so if you also want to change WriteConfig
to not take an int id
, then you'll need to make the deleteFunc
into Action
instead of Action<int>
, so: 所以,如果你也想改变
WriteConfig
不采取int id
,那么你就需要让deleteFunc
成Action
,而不是Action<int>
,所以:
public void WriteConfig(string fileName, BlockingCollection<byte[]> queue,
Action deleteFunc)
and 和
var task = fac.StartNew(() => { vault.WriteConfig(fileName, queue,
() => DeleteUploadQueue(id)); })
You´re looking from the whrong point. 您正在从错误的角度出发。 You should provide the arguments for the delegate when you´re calling it, not when you´re defining it.
您应该在调用委托时提供委托的参数,而不是在定义委托时提供参数。 I suppose this happens within your
WriteConfig
-method: 我想这是在您的
WriteConfig
方法中发生的:
WriteConfig(string fileName, int id, BlockingCollection<byte[]> queue, Action<int> deleteFunc)
{
/* ... */
deleteFunc(id) <------- provide your args here
}
Providing the parameter to your delegate happens at the line marked with <-------
. 将参数提供给您的代表发生在标有
<-------
的行上。 Yimply provide the id
: 只需提供
id
:
deleteFunc(id);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.