zoukankan      html  css  js  c++  java
  • 扩展方法

     1 using System;
     2 using System.Collections.Generic;
     3 using System.Linq;
     4 using System.Text;
     5 using System.Threading.Tasks;
     6 
     7 namespace LinqToSql
     8 {
     9     /// <summary>
    10     /// 如果引用第三方的类文件,可以给该类文件添加自己的扩展方法,逼格杠杠的
    11     /// 
    12     /// 不能滥用
    13     /// </summary>
    14     public static class ExtendsShow
    15     {
    16         /// <summary>
    17         /// 扩展方法:静态类里的静态方法,第一个参数类型前面加上this
    18         /// </summary>
    19         /// <param name="data">int? 表示可以添加具体值,也可以为空null</param>
    20         /// <returns>data ?? -1: 表示如果给参数data赋值为null,那么返回-1,如果赋值为具体某个值,就返回赋值的结果</returns>
    21         public static int ToInt(this int? data)
    22         {
    23             return data ?? -1;
    24         }
    25 
    26         /// <summary>
    27         /// 该方法只能扩展第一个参数类型,不能扩展后面的
    28         /// 给LamdaShow类进行扩展
    29         /// </summary>
    30         /// <param name="lamda"></param>
    31         /// <param name="iParameter"></param>
    32         /// <param name="sParameter"></param>
    33         public static void ExtendLamdaShow(this LamdaShow lamda, int iParameter, string sParameter)
    34         {
    35             Console.WriteLine($"LamdaShow=={ iParameter}==={ sParameter }");
    36         }
    37     }
    38 }

    上端主程序调用

     1 using System;
     2 using System.Collections.Generic;
     3 using System.Linq;
     4 using System.Text;
     5 
     6 namespace LinqToSql
     7 {
     8     class Program
     9     {
    10         static void Main(string[] args)
    11         {
    12             //int类型调用扩展方法
    13             int? data = null;
    14             int? other = 2;
    15             Console.WriteLine(ExtendsShow.ToInt(data));
    16             Console.WriteLine(other.ToInt());
    17             Console.ReadLine();
    18 
    19             //LamdaShow其他类调用扩展方法
    20             new LamdaShow().ExtendLamdaShow(123, "张三");
    21         }
    22     }
    23 }
    View Code


    第三方类

     1 using System;
     2 using System.Collections.Generic;
     3 using System.Linq;
     4 using System.Text;
     5 using System.Threading.Tasks;
     6 
     7 namespace LinqToSql
     8 {
     9     public class LamdaShow
    10     {
    11 
    12     }
    13 }
    View Code
    世界上最可怕事情是比我们优秀的人比我们还努力
  • 相关阅读:
    MongoDB-基础-limit-skip-sort
    MongoDB-基础-条件操作符
    mongodb-基础-update-remove
    Linq to sql-存储过程
    SQL Server-游标使用
    JavaScript-求时间差
    HTTP 错误 500.21
    .NET错误The 'targetFramework' attribute in the <compilation> element of the Web.config file is used only to target version 4.0 and later of the .NET Framework
    HTTP 错误 500.21
    WebApi&MVC对比
  • 原文地址:https://www.cnblogs.com/AlexOneBlogs/p/7387972.html
Copyright © 2011-2022 走看看