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

    如果现有的一个类,想给它加上新的函数,原有的方式是从现有的一个类继承一个新的类,在新的类中加入需要的函数,现在提供了新的方式给现有的类添加函数而且不用继承,这就是扩展方法。现以扩展String类为例,给String类加一个判断是否为电子邮件格式的函数。

    首先新增一个类,如下

    /// <summary>
    /// 类和方法都必须是静态的,方法参数前有“this”,表示附加到实例上去
    /// </summary>
    public static class ScottGuExtensions
    {
        public static bool IsValidEmailAddress(this string s)
        {
            Regex regex = new Regex(@"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$");
            return regex.IsMatch(s);
        }
    }

    你也可以为用此类的办法去判断DataSet是否为空,是否有表。

    public static class ScottGuExtensions
    {
        public static bool isDataSetValid(this DataSet  ds)
        {
            if (ds != null && ds.Tables.Count > 0)
            {
                return true;
            }
            return false;
        }
    }
    DataSet ds = GetDataSet();//获取DataSet的方法
    ds.IsDataSetValid(ds);
  • 相关阅读:
    EF Core 原理从源码出发(一)
    EF Core 原理从源码出发(二)
    AutoMapper的源码分析
    Latex 引用为名字+序号
    Latex引用文献按照引用顺序排序
    HttpRunner3.X
    Python Selenium — 封装浏览器引擎类
    Online PCA for Contaminated Data
    LEARNING WITH AMIGO: ADVERSARIALLY MOTIVATED INTRINSIC GOALS
    LEARNING INVARIANT REPRESENTATIONS FOR REINFORCEMENT LEARNING WITHOUT RECONSTRUCTION
  • 原文地址:https://www.cnblogs.com/pnljs/p/2933725.html
Copyright © 2011-2022 走看看