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

    1、扩展方法必须写在静态类中

    2、扩展方法也必须是静态方法

    3、方法参数第一个为需要添加静态方法的类

    //1.扩展方法必须写到静态类中。
    static class StringExt
    {
    //2.扩展方法也必须是静态方法
    //第一个参数表示要给哪个类型增加一个扩展方法 this 类型 变量
    public static bool IsEmail(this string emailStr)
    {
    return Regex.IsMatch(emailStr, @"^w+@w+.w+$");
    }


    public static bool IsPostcode(this string postStr)
    {
    return Regex.IsMatch(postStr, @"^d{6}$");
    }

    public static void SayHi(this Person p)
    {
    //扩展方法是不能访问原来类中的私有成员的。
    Console.WriteLine("大家好,我是:{0}", p.Name);
    }

    public static void SayHello(this Person p, string msg, int n)
    {
    Console.WriteLine("{0}--{1}", msg, n);
    }

    }

    用方式:

    class Program
    {
    static void Main(string[] args)
    {
    string str = "zxh@itcast.cn";

    string str1 = "100193";

    if (str.IsEmail())
    {
    Console.WriteLine("yes");
    }
    else
    {
    Console.WriteLine("no");
    }
    Console.ReadKey();

    //if (str1.IsPostcode())
    //{

    //}


    int[] arrInt = new int[] { 1, 2, 32 };
    // arrInt.Count(
    Person p = new Person();
    p.Name = "zxh";
    p.SayHi();
    p.SayHello("aaaaaaaa", 1000);
    Console.ReadKey();
    }
    }
    public class Person
    {
    public void Test1()
    {
    score = 10;
    }

    private int score;

    public string Name
    {
    get;
    set;
    }
    public int Age
    {
    get;
    set;
    }
    public string Email
    {
    get;
    set;
    }

    }

      扩展方法

    1)        扩展方法声明在静态类中,定义为一个静态方法,其第一个参数需要使用this关键字标识,指示它所扩展的类型。

    2)  扩展方法可以将方法写入最初没有提供该方法的类中。还可以把方法添加到实现某个接口的任何类中,这样多个类就可以使用相同的实现代码。(LINQ中,System.Linq.Queryable.cs和System.Linq.Enumerable.cs 正是对接口添加扩展方法)

    3)        扩展方法虽定义为一个静态方法,但其调用时不必提供定义静态方法的类名,只需引入对应的命名空间,访问方式同实例方法。

    4)        扩展方法不能访问它所扩展的类型的私有成员。

  • 相关阅读:
    Linux:CentOS-7配置VMware-15.5与本机IP同网段
    SpringCloud:Zuul路由配置超时问题
    SpringCloud:路由ZUUL的配置详解
    SpringCloud:扩展zuul配置路由访问
    给source insight添加.cc的C++文件后缀识别(转载)
    Linux下共享库嵌套依赖问题 (转载)
    Ubuntu 下编译libjingle-0.6.14 (转载)
    什么是「穷人思维」?
    谁上北大是能力说了算,不该是教育部(转载)
    Installing cmake 2.8.8 or higher on Ubuntu 12.04 (Precise Pangolin) (转载)
  • 原文地址:https://www.cnblogs.com/puweibuqi/p/3771267.html
Copyright © 2011-2022 走看看