zoukankan      html  css  js  c++  java
  • C# 扩展类

    C# 中提供一个非常实用的供能,扩展方法(Extension method)

    扩展方法是通过额外的静态方法扩展现有的类型。通过扩展方法,可以对已有类型做自己想做的相关扩展。方法:定义静态类,扩展方法也要是静态方法,并且扩展方法的第一个参数为要扩展的类型,必须附加一个this关键字。

    举例如下: 

    扩展类:

        public static class Extend
        {
    
            public static bool IsNullOrEmpty(this object i)
            {
                if (i == null) return true;
    
                if (i.GetType() == typeof(string))
                {
                    string temp = (string)i;
                    return temp.IsNullOrEmpty();
                }
                else return false;
            }
    
            public static Guid ToGuid(this string i)
            {
                Guid id;
                if (!Guid.TryParse(i, out id))
                {
                    throw new Exception(i + " can not be converted to Guid");
                }
                return id;
            }
        }

    扩展方法调用:

        public class TestExtend
        {
            public void Test()
            {
                string i = "this a world for me";
                Console.Write(i.ToGuid());
                try
                {
                    Guid guid = i.ToGuid();
                    Console.Write(guid.ToString());
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
        }
  • 相关阅读:
    修改CentOs开机启动时的timeout
    各种快捷键
    测试实例异常
    测试实例异常
    springBoot中测试类的头注解
    学习笔记9
    stat命令的实现-mystat
    反汇编测试
    学习笔记7
    openssl截图
  • 原文地址:https://www.cnblogs.com/feuji/p/4149227.html
Copyright © 2011-2022 走看看