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);
                }
            }
        }
  • 相关阅读:
    [SCOI2003]严格N元树
    CF280 C. Game on Tree
    [HDU2281]Square Number
    [HDU5391]Zball in Tina Town
    [HDU3988]Harry Potter and the Hide Story
    [HDU5794]A Simple Chess
    [HDU5451]Best Solver
    [HDU1724]Ellipse
    [HDU6304]Chiaki Sequence Revisited
    [HDU6343]Graph Theory Homework
  • 原文地址:https://www.cnblogs.com/feuji/p/4149227.html
Copyright © 2011-2022 走看看