Func<string, string> checkAffairCode = oldAffairCodeStr =>
{
string newAffairCodeStr = "";
if (oldAffairCodeStr != "")
{
string[] affairCodeArr = oldAffairCodeStr.Split(';');
foreach (string affaircode in affairCodeArr)
{
var affairsInfo = db.affairs.Where(x => x.AFFAIRCODE == affaircode).FirstOrDefault();
if (affairsInfo != null)
{
newAffairCodeStr += newAffairCodeStr == "" ? affaircode : ";" + affaircode;
}
}
}
return newAffairCodeStr;
};
调用方法:上面的方法是定义在方法中,并且可以在下面的代码中调用
官网地址:https://docs.microsoft.com/zh-cn/dotnet/api/system.func-2?view=netframework-4.7.2
public ActionResult Index()
{
ces a = new ces() { id = 0, name = "default" };
result re = new result(Result2);
a = re.Invoke(a);//这句和下面一句的调用完全一样,写法不同而已
a = re(a);
result re2 = new result(Result3);
a = re2.Invoke(a);
result0 re3 = new result0(Result4);
a = re3.Invoke(ref a);
return View();
}
public static void Result1(ces a)
{
a.id = 1;
a.name = "result2";
}
public static ces Result2(ces a)
{
a.id = 1;
a.name = "result2";
return a;
}
public static ces Result3(ces a)
{
a = new ces();
a.id = 2;
a.name = "result3";
return a;
}
public static ces Result4(ref ces a)
{
a = new ces();
a.id = 3;
a.name = "result4";
return a;
}
public delegate ces result(ces a);
public delegate ces result0(ref ces a);
public class ces
{
public int id { get; set; }
public string name { get; set; }
}
简单委托定义及调用,这个是在一次面试中出现过类似的问题,当时对于委托有些模糊
https://www.cnblogs.com/kewolf/p/4695889.html
这篇文章讲解的比较详细
当存在多个参数的时候,比如获取两个int参数和的平方
Func<int, int, int> func = (int1, int2) =>
{
return (int)Math.Pow(int1 + int2, 2);
};
int a = func(5, 2);//a=49