zoukankan      html  css  js  c++  java
  • C#基础知识---扩展方法

    一、简介

    扩展方法为现有的类型(.Net类型或者自定义类型)扩展应该附加到该类型中的方法。

    二、基本原则

    • 定义一个非嵌套非泛型静态类
    • 扩展方法是静态的
    • 扩展方法至少要有一个参数,该参数类型是要扩展的类型
    • 第一个参数必须加上this关键字作为前缀
    • 第一个参数不能用其他任何修饰符(如不能使用ref out等修饰符)
    • 第一个参数的类型不能是指针类型

    三、例子

      例1:为.Net类型添加扩展方法

     1 using System;
     2 
     3 namespace ExtensionMethod
     4 {
     5     class Program
     6     {
     7         static void Main(string[] args)
     8         {
     9             string myStr = "YuanXi";
    10             string tmpStr1 = myStr.GetNotNullString();
    11             Console.WriteLine(tmpStr1);
    12 
    13             myStr = null;
    14             tmpStr1 = myStr.GetNotNullString();
    15             Console.WriteLine(tmpStr1);
    16         }
    17     }
    18     public static class StringExtension
    19     {
    20         public static string GetNotNullString(this string str)
    21         {
    22             return str ?? string.Empty;
    23         }
    24     }
    25 }
    View Code

      例2:为自定义类型添加扩展方法

      

     1 using System;
     2 
     3 namespace ExtensionMethod
     4 {
     5     class Program
     6     {
     7         static void Main(string[] args)
     8         {
     9             int a = 4;
    10             int b = 1;
    11             Calculator cal = new Calculator();
    12             int r = cal.Add(a, b);
    13             int r2 = cal.Sub(a, b);
    14             Console.WriteLine($"Add result is: {r}");
    15             Console.WriteLine($"Sub result is: {r2}");
    16         }
    17     }
    18     public class Calculator
    19     {
    20         public int Add(int a, int b)
    21         {
    22             return a + b;
    23         }
    24     }
    25     public static class CalculatorExtension
    26     {
    27         public static int Sub(this Calculator cal, int a, int b)
    28         {
    29             return a - b;
    30         }
    31     }
    32     public static class StringExtension
    33     {
    34         public static string GetNotNullString(this string str)
    35         {
    36             return str ?? string.Empty;
    37         }
    38     }
    39 }
    View Code

      

  • 相关阅读:
    全新 D 系列虚拟机型号
    D 系列性能预期
    Azure Backup 入门
    对 Azure Backup 的常见配置问题进行故障排除
    宣布发布长期保留 Azure Backup功能
    宣布 Azure Backup 支持备份 Windows Server 2008
    Azure Backup 简介
    MongoDB中ObjectId的误区,以及引起的一系列问题
    UNIX/Linux_C_程序员需要掌握的七种武器
    Docker企业版安装指南
  • 原文地址:https://www.cnblogs.com/3xiaolonglong/p/9662452.html
Copyright © 2011-2022 走看看