delegate-使用笔记

public class testclass
{
    public class ProductImages : Page
    {
        protected Repeater rptSmallUrls;
        protected Repeater rptBigUrls;
        /// <summary>
        /// 委托
        /// </summary>
        /// <param name="url"></param>
        delegate void AddUrl(string url);

        protected void Page_Load(object sender, EventArgs e)
        {
            int productId = 0;
            int.TryParse(this.Page.Request.QueryString["ProductId"], out productId);

            if (!this.Page.IsPostBack)
            {
                //获取数据
                ProductInfo productSimpleInfo = ProductBrowser.GetProductSimpleInfo(productId);
                //绑定相册
                if (productSimpleInfo != null)
                {
                    this.BindImages(productSimpleInfo);
                }
            }

        }

        private void BindImages(ProductInfo productImageInfo)
        {
            //加载大图
            List<string> bigList = new List<string>();
            AddUrl addUrlToList = delegate (string url)//向List中添加Url的匿名方法
            {
                if (!string.IsNullOrEmpty(url))
                {
                    bigList.Add(url);
                }
            };
            addUrlToList(productImageInfo.ImageUrl1);
            addUrlToList(productImageInfo.ImageUrl2);
            addUrlToList(productImageInfo.ImageUrl3);
            addUrlToList(productImageInfo.ImageUrl4);
            addUrlToList(productImageInfo.ImageUrl5);
            addUrlToList(productImageInfo.ImageUrl6);
            if (productImageInfo.Spread != null && !string.IsNullOrEmpty(productImageInfo.Spread.Images))
            {
                bigList.AddRange(productImageInfo.Spread.Images.TrimEnd(',').Split(','));
            }
            this.rptBigUrls.DataSource = bigList;
            this.rptBigUrls.DataBind();

            //加载小图
            List<string> smallList = new List<string>();
            bigList.ForEach(u => smallList.Add(u.Replace("/product/images/", "/product/thumbs40/40_").Replace("/pet/images/", "/pet/thumbs40/40_")));
            this.rptSmallUrls.DataSource = smallList;
            this.rptSmallUrls.DataBind();
        }
    }
}
View Code

实际使用到的delegate的两种用法。

记录以供参考。

一、

//声明

delegate void AddUrl(string url);

//定义

AddUrl addUrlToList = delegate (string url)
{
  if (!string.IsNullOrEmpty(url))
  {
    bigList.Add(url);
  }
};

//调用

addUrlToList(productImageInfo.ImageUrl1);

二、

//匿名调用

bigList.ForEach(u => smallList.Add(u.Replace("/product/images/", "/product/thumbs40/40_").Replace("/pet/images/", "/pet/thumbs40/40_")));

原文地址:https://www.cnblogs.com/huhunet/p/5976159.html