[英].NET Core - BLAZOR - Custom component - Store async Task in dictionary for later usage with EventCallback
我有一个定制的 Blazor 组件,它有一个带参数的字典。
它是一个通用组件,位于主布局<SharedComponent></SharedComponent>
中。
该组件在其中呈现另一个组件并通过字典传递参数 - 在下面的代码行中, dic 是parameters
。 以下代码呈现子组件。
ComponentService.Add<ChildComponent>(text, parameters, taskParameters);
PS:有两个字典: - 一个用于普通参数; - 一个用于功能。
我认为应该如何实现:
Func
委托的字典中。我的问题:
这是完全正确的方法还是有其他方法?
到目前为止我已经尝试过什么,我需要一些帮助......
这是字典:
public class ComponentTaskParameters
{
private Dictionary<string, Func<Task>> taskPparameters;
public ComponentTaskParameters()
{
taskPparameters = new Dictionary<string, Func<Task>>();
}
public void Add(string parameterName, Func<Task> value)
{
taskPparameters[parameterName] = value;
}
public Func<Task<T>> Get<T>(string parameterName)
{
if (!taskPparameters.ContainsKey(parameterName))
{
throw new KeyNotFoundException($"{parameterName} does not exist in component parameters");
}
return (Func<Task<T>>)taskPparameters[parameterName];
}
}
假设这是异步 function:
async Task SaveItem(Item item)
{
// save code
}
我试图用Func
和Action
将它存储到字典中,但没有运气。
我怎么能做到这一点,它是否可以实现?
我创建了一个代表
delegate Item SaveItemDelegate(Func<Task, Item> saveTask);
我无法将检索到的 function 从字典中添加到委托中。
这是我创建EventCallback
的方法
var callbackEvent = new EventCallback<Item>(null, saveItemDelegate);
而且我无法使用CallbackEvent.InvokeAsync(Item);
.
感谢这里的所有帮助。
谢谢!
解决方案是将 SaveItem function 作为多播委托存储在字典中。
// Insert into dict function
public void Add(string parameterName, MulticastDelegate value)
{
taskPparameters[parameterName] = value;
}
// Declaration of the delegate
public delegate Task SaveDelegate(Item item);
// New delegate
SaveDelegate saveDelegate = new SaveDelegate(SaveItem);
// Store the delegate in the dictionary
taskParameters.Add("CallbackFunction", saveDelegate);
然后我能够检索它并将其传递给EventCallback
。 然后成功调用它。
// Pull out from the dict function
public MulticastDelegate Get(string parameterName)
{
return taskPparameters[parameterName];
}
// The delegate
MulticastDelegate save = TaskParameters.Get("CallbackFunction");
// Create new 'EventCallback'
EventCallback callback = new EventCallback(null, save);
// Invoke the 'EventCallback'
callback.InvokeAsync(item);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.