Func是一个委托,委托里面可以存方法,Func<string,string>或Func<string,string,int,string>等
前几个是输入参数,最后一个是返回参数
以Func<int,bool>为例:
private bool IsNumberLessThen5(int number)
{return number < 5;}
Func<int,bool> f1 = IsNUmberLessThen5;
调用:
bool flag= f1(4);
//以下是其它的用法,与IsNumberLessThen5作用相同。只是写法不同而已。
Func<int, bool> f2 = i => i < 5;
Func<int, bool> f3 = (i) => { return i < 5; };
Func<int, bool> f4 = delegate(int i) { return i < 5; };
多参数的使用方法
Func<int,int ,int> Coun = (x,y) =>
{
return x + y;
};
自己项目中实例
类库的一个方法需要用到Server.MapPath返回的路径,但是类库中无法直接使用Server.MapPath方法
于是在web中定义一个方法,接收一个相对路径字符串,返回相对于根目录的字符串
Func<string, string> getphysicsPath = p => { return Server.MapPath(p); }; ---------------------------------------------- //或采用常规写法 public string getphysicsPath(string p) { return Server.MapPath(p); };
在类库的中:
public class SaveUploadFile { public static string SaveImage(HttpPostedFileBase file, Func<string, string> getPath) { DateTime now = DateTime.Now; string newFileName = string.Empty; string fileType = Path.GetExtension(file.FileName); string suijishu = Math.Abs(Guid.NewGuid().GetHashCode()).ToString(); newFileName = now.ToString("yyyyMMddHHmmss") + "_" + suijishu + fileType; string path = CommConfig.UploadImageUrl + "/" + now.ToString("yyyyMMdd"); string physicsPath = getPath(path);//调用传入的方法计算路径 string fullPath = physicsPath + "/" + newFileName; string newFilePath = path + "/" + newFileName; if (!Directory.Exists(physicsPath)) { Directory.CreateDirectory(physicsPath); } file.SaveAs(fullPath); return newFilePath; } }
最后在web中
var file = Request.Files[0]; string newFilePath= SaveUploadFile.SaveImage(file, getphysicsPath);
==============================================================================
自己的理解总结:
假如有2个不同的类库A和B,类库A使用了类库B中的方法method1
类库A中可以调用某个库函数,而类库B中无法调用
如上例中的Server.MapPath(‘xxx’),只能在web类库中调用
假如类库B中方法method1中需要使用Server.MapPath()
首先:
在类库A中定义一个方法
//定义一个满足委托格式的方法 public string GetPaht(string p) { return Server.MapPath(p); } //类库A调用类库B中的method1方法 ClassA a = new ClassA(); //ClassA是类库B中的类 a.method1("aa",GetPaht);
然后在类库B中的method1方法的参数中多增加一个委托类参数Func<string,string> (最后一个是返回值类型,前面的都是输入值类型)如下:
public void method1(string param, Func<string,string> getPath) { xxxxx xxxxx string path = getPath('xxxxx');//相当于调用Server.MapPath(p); xxxxx xxxxx }