[英]Is it possible to send a function to another function with the same return type but different parameters?
I have an AttachmentService.cs class that is currently used to upload images to a database and/or a cloud storage container. 我有一个AttachmentService.cs类,当前用于将图像上传到数据库和/或云存储容器。 When uploading to the cloud I have some retry logic in place that I would like to reuse when being called by two separate methods.
当上传到云中时,我有一些重试逻辑,当被两个单独的方法调用时,我想重用这些逻辑。 I would like to pass in each function as a parameter and then call them from within the method they have been passed into.
我想将每个函数作为参数传入,然后从它们已传入的方法中调用它们。 Here are the two signatures I have currently:
这是我目前拥有的两个签名:
C# C#
//Example: I want to be able to pass the first function and also the second
//I'm sure it can done with generics but can't seem to get it currently
private AttachmentUploadResult UploadAttachmentToGLS(Func<string, Guid, byte?[], string, AttachmentUploadResult> uploadFunction)
private AttachmentUploadResult UploadAttachmentToGLS(Func<AttachmentEntity, AttachmentUploadResult> uploadFunction)
I would like the above code to only have one signature that could take either 我希望上面的代码只有一个签名可以使用
Func<string, Guid, byte?[], string, AttachmentUploadResult> uploadFunction
or Func<AttachmentEntity, AttachmentUploadResult> uploadFunction
so that my method could look like something like this: Func<string, Guid, byte?[], string, AttachmentUploadResult> uploadFunction
或Func<AttachmentEntity, AttachmentUploadResult> uploadFunction
这样我的方法看起来像这样:
private AttachmentUploadResult UploadAttachmentToGLS(Func<parameters, AttachmentUploadResult>uploadFunction)
{
//Some retry logic
uploadFunction(parameters);
//Some more retry logic
}
Is there a way in which I can acheive the above? 有什么方法可以达到上述目的? I have read into Func and do not believe this is the correct delegate to use.
我已经读过Func,但不认为这是使用的正确委托。
The signature of your function can be just Func<AttachmentUploadResult>
- you don't really care about the parameters in the UploadAttachment
method, so you should close over them. 函数的签名可以只是
Func<AttachmentUploadResult>
-您实际上并不关心UploadAttachment
方法中的参数,因此应将其关闭。 The call might then look something like this: 然后,呼叫可能看起来像这样:
Upload(() => SomeUploadMethod(theActual, parameters, toTheMethod));
It also allows you to hide the details of the implementation from the UploadAttachment
method - all you care about is "this is the function to call when I want to do the upload". 它还允许您从
UploadAttachment
方法中隐藏实现的详细信息-您关心的只是“这是我要执行上载时要调用的函数”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.