c# 扩展方法

    /// <summary>
    /// ConcurrentDictionary扩展 按照使用Dictionary Remove Add
    /// </summary>
    public static class ConcurrentDictionaryExt
    {

        public static bool Remove<TKey, TValue>(this ConcurrentDictionary<TKey, TValue> self, TKey key)
        {
            TValue ignored;
            return self.TryRemove(key, out ignored);
        }
        public static bool Add<TKey, TValue>(this ConcurrentDictionary<TKey,TValue> self, TKey key,TValue value)
        {
            return self.TryAdd(key, value);
        }
    }

    public static class DateTimeExt
    {
        /// <summary>
        /// 年月日时分秒毫秒
        /// </summary>
        /// <param name="dateTime"></param>
        /// <returns></returns>
        public static string ToYMDHMSFTimeString(this DateTime dateTime)
        {
            return dateTime.ToString("yyyy - MM - dd hh: mm:ss: fff");
        }
        /// <summary>
        /// 年月日时分秒
        /// </summary>
        /// <param name="dateTime"></param>
        /// <returns></returns>
        public static string ToYMDHMSTimeString(this DateTime dateTime)
        {
            return dateTime.ToString("yyyy - MM - dd hh: mm:ss");
        }
    }

上面是俩个扩展方法的定义

下面是如何使用

            string time = DateTime.Now.ToYMDHMSFTimeString();
            ConcurrentDictionary<int, string> alarmInfoDic = new ConcurrentDictionary<int, string>();

            alarmInfoDic.Add(1, "test1");
            alarmInfoDic.Add(2, "test2");
            alarmInfoDic.Remove(1);

 

应用场景:在不修改源类代码情况,通过ADD File 模式对源代码功能扩展。

扩展方法要求如下:

a.扩展方法需包含在 static 修饰类中.

b.扩展实现需是静态形式。

c.扩展方法第一个参数 前缀为 this , 表示需要扩展类对象,从第二个参数开始,为扩展方法参数列表

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值