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

    演示代码:

    public class Program
        {
            static void Main(string[] args)
            {
                var txt = "hello";
                Console.WriteLine(txt.GetString());
                var inttxt = "123";
                Console.WriteLine(inttxt.GetInt());
                var inttxt1 = "asd";
                Console.WriteLine(inttxt1.GetInt());
                Console.WriteLine("234".GetInt());
                Console.WriteLine("qwe".GetInt());
            }
    
        }
    
        public static class ExString
        {
            public static string GetString(this string source)
            {
                return source + "扩展方法";
            }
    
            public static int GetInt(this string source)
            {
                var outint = 0;
                if (!string.IsNullOrEmpty(source))
                {
                    var result = int.TryParse(source,out outint);
                    return outint;
                }
                return outint;
            }
        }
    

      代码输出:

     演示代码二:

    public class Program
        {
            static void Main(string[] args)
            {
                var test = "dddd";
                Console.WriteLine(test.GetFuncString(x=>x=="123"));
                test = "123";
                Console.WriteLine(test.GetFuncString(x=>x=="123"));
            }
    
    
        }
    
        public static class ExString
        {
    
            public static string GetFuncString(this string source, Func<string, bool> type )
            {
                if (type(source))
                {
                    return "true";
                }
                return source;
            }
        }

    运行结果:

    说明:

    1、扩展方法是属于静态类的静态方法

    2、第一个参数 this关键字,参数类型是需要扩展的类型

  • 相关阅读:
    Chapter 14_2 全局变量声明
    chapter 14_1 环境
    chapter 13_4 跟踪table的访问
    Linq to Entity 和 Linq to Object 异同
    ADO.net实体类操作
    XML
    JavaScript
    CSS样式表
    HTML
    java 反射
  • 原文地址:https://www.cnblogs.com/fuyujian/p/4394305.html
Copyright © 2011-2022 走看看