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

    扩展方法使您能够向现有类型“添加”方法,而无需创建新的派生类型、重新编译或以其他方式修改原始类型。扩展方法是一种特殊的静态方法,但可以像扩展类型上的实例方法一样进行调用。

    1.可以使用扩展方法来扩展类或接口,但不能重写扩展方法。

      2.与接口或类方法具有相同名称和签名的扩展方法永远不会被调用。

      3.编译时,扩展方法的优先级总是比类型本身中定义的实例方法低。

        换句话说,如果某个类型具有一个名为Process(int i) 的方法,而您有一个具有相同签名的扩展方法,则编译器总是绑定该实例方法。

      4.当编译器遇到方法调用时,它首先在该类型的实例方法中寻找匹配的方法。

        如果未找到任何匹配方法,编译器将搜索为该类型定义的任何扩展方法,并且绑定到它找到的第一个扩展方法

    namespace Demo
    {
        class Program
        {
            static void Main(string[] args)
            {
                var stu = new Student() { Name = "joey", Age = 25 };
                //调用实例方法
                Console.WriteLine(stu.ToString());
                //调用扩展方法 。调用的时候会vs 智能感知会在方法边上加个向下的箭头,表示这是一个扩展方法
                Console.WriteLine(stu.Hello());
            }
        }
        public class Student
        {
            public string Name { get; set; }
            public int Age { get; set; }
            //重写ToString方法
            public new string ToString()
            {
                return "Name: " + this.Name + "
    Age: " + this.Age;
            }
        }
    
        public static class ExtendMehods
        {
            //使用this 关键字扩展类的方法
            public static string Hello(this Student stu)
            {
                return "嗨!大家好!我叫 " + stu.Name + ",我今年 " + stu.Age + "";
            }
        }
    }
  • 相关阅读:
    C#读取Excel日期时间
    软件需求3个层次――业务需求、用户需求和功能需求
    软件开发中的基线
    软件开发过程(CMMI/RUP/XP/MSF)是与非
    第1章项目初始.pdf
    计算机鼓轮
    概念模型,逻辑模型,物理模型
    第0章项目管理概述.pdf
    C#中提供的精准测试程序运行时间的类Stopwatch
    Installing and configuring OpenSSH with pam_ldap for RedHat Enterprise Linux3
  • 原文地址:https://www.cnblogs.com/ecollab/p/6225183.html
Copyright © 2011-2022 走看看