zoukankan      html  css  js  c++  java
  • Func<>用法

    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 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);
    

      

  • 相关阅读:
    JavaScript 弹窗
    创建对象构造器
    DOM事件
    document对象“还在更新”
    JavaScript 闭包
    使用 "use strict" 指令
    constructor 属性
    2019暑期集训第一周小结
    无向图求割边
    矩阵快速幂
  • 原文地址:https://www.cnblogs.com/fireicesion/p/14660515.html
Copyright © 2011-2022 走看看