[英]c# Func Delegate - how to pass the value in generics
我想在接口中使用 Func - 泛型。 根據輸入,我想處理操作。 但不知何故我無法在函數中獲得輸入。
1) 我將 Func<> 作為參數傳遞的用例應該是什么? 2) 返回 Fuc<> 作為返回對象有什么好處?
我創建了一個界面。
public interface IAutoFacDemo
{
Task<string> GetAsync(Func<string, Task<string>> concat, string input);
}
其中有一個具體的實現
public class BusConcat : IAutoFacDemo
{
#region Implementation of IAutoFacDemo
public BusConcat()
{
}
// ?? 我無法從程序中提取輸入字符串“dinesh” // 我將它作為 lambda 表達式傳遞
public async Task<string> GetAsync(Func<string, Task<string>> concat, string input)
{
var v = Function(concat, input).Result;
return (v);
}
private static async Task<string> Function(Func<string, Task<string>> bus, string input)
{
var v = await bus(Process("").Result).ConfigureAwait(false);
return v;
}
private static async Task<string> Process(string input)
{
return Task.FromResult( ":").Result;
}
#endregion
}
然后為了使用該接口,我為 Autofac 模塊加載創建了另一個接口
public interface IFactory
{
Task<string> GetValue(Func<string,Task<string>> fn,string input);
}
並且從主要
static void Main(string[] args)
{
var scope = AutoFacContainerConfig.RegisterLifetimeScope();
{
using (var resolveEntity = scope.BeginLifetimeScope())
{
var names =new List<string>{"dinesh","tripathi","avenue"};
var factory = resolveEntity.Resolve<IFactory>();
Console.WriteLine(factory.GetType().ToString());
var x = string.Empty;
var v=(x.Insert(0, names.First(xc => xc.Contains("dinesh"))));
// I am trying to call the Func<string,Task<string>> where i want to pass
//the list if it contains "dinesh" to the function and based on the string
//it will process the function
var xx = factory.GetValue(async i=>i+await Task.FromResult(names.First(x1=>x1.Contains("dinesh"))),"Test").Result;
Console.WriteLine(xx);
}
}
}
我得到 dinesh:Test 作為輸出,但我想在將字符串作為 lambda 值傳遞給 Func 時處理“dinesh”
偉大的。 知道了 。 在函數 GetAsync 中獲取 lambda 值“dinesh”
我聲明了字符串變量並在 Concat 上調用 Invoke 來獲得結果。
string ret=string.empty
var retVal=concat.Invoke(ret).Result
從 lambda 表達式傳遞給我的“dinesh”。
謝謝大家。 :)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.