• 扩展方法


    如果现有的一个类,想给它加上新的函数,原有的方式是从现有的一个类继承一个新的类,在新的类中加入需要的函数,现在提供了新的方式给现有的类添加函数而且不用继承,这就是扩展方法。现以扩展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);
  • 相关阅读:
    SpringBoot自动装配
    Docker容器添加对外映射端口
    Day03 腿部训练
    Day04 胸 + 肩部训练
    Day02 背 + 二头肌
    @Transactional注解失效场景
    Docker快速安装RocketMQ
    Linux 命令 速记
    Window Phone 7 设备的方向
    使用异步代理+IAsyncResult 调用函数
  • 原文地址:https://www.cnblogs.com/pnljs/p/2933725.html
Copyright © 2020-2023  润新知