0
点赞
收藏
分享

微信扫一扫

面向对象——扩展方法

gy2006_sw 2022-03-21 阅读 134


  C#扩展方法:

    1 方法所在的类必须是静态的

    2 方法也必须是静态的

    3 方法的第一个参数必须是你要扩展的那个类型,比如你要给int扩展一个方法,那么第一个参数就必须是int。

    4 在第一个参数前面还需要有一个this关键字。

例:

public static class PropertyExtension

    {

        public static object GetValueByName(this object self, string propertyName)

        {

            if (self == null)

            {

                return self;

            }

            Type t = self.GetType();

            PropertyInfo p = t.GetProperty(propertyName);

            return p.GetValue(self, null);

        }

    }

    class Program

    {

        static void Main(string[] args)

        {

            string str = "abc";

            object len = str.GetValueByName("Length");

            Console.WriteLine(len.ToString());

        }

}  

输出结果:

3

C#扩展方法使用的原则:

  1. C#扩展方法有就近原则,也就是你的程序一模一样的C#的扩展方法,一个和你使用的子类处于同一命名空间里,另外一个处于别的命名空间里,这个时候就会优先使用同一命名空间的C#扩展方法,也就是说“血缘关系”越近,越被青睐。
  2. 扩展方法是一个补丁作用,在一个进程(一个程序集)的范围内,给某个类型临时加上方法。所以扩展方法不能写在嵌套类,应该在程序集的全局区,这个程序集的顶级类中。而且要有二(在static类中,是一个static方法),this是它和一般方法的区别符。
  3. 扩展方法当然不能破坏面向对象封装的概念,所以只能访问扩展类的public成员。
  4. 有两种使用方法,例:

   public static class ExtendMethod

    {

        public static void Fun(this string s)

        {

            Console.WriteLine(s);

        }

    }

    class Program

    {

        static void Main(string[] args)

        {

            string str = "abc";

            str.Fun();

            ExtendMethod.Fun(str);

        }

 }

注意:使用s.Fun();这种形式调用更能体现扩展方法的意味。使用ExtendMethod.fun(s);这种形式调用,则更能体现扩展方法实现的本质,便于理解为什么是只能访问锁扩展类型的public成员。

LINQ的实现正是基于扩展方法,实现原理为:

在一个基类上进行扩展,一般而言扩展方法单独地建立一个命名空间,在使用的时候,导入这个命名空间,则开启了扩展方法的可见性,这个时候,所有子类便可以使用这个扩展方法了(因为子类继承了基类,public,static这样的权限级别更是很容易的满足直接调用)

  class User

    {

        public string Name { get; set; }

        public int Age { get; set; }

        public double Pay { get; set; }

        public override string ToString()

        {

            return string.Format("姓名:{0} 年龄:{1} 工资:{2}", Name, Age, Pay);

        }

    }

    static class ShowInfo

    {

        public static void Display(this object o)

        {

            Console.WriteLine(o.ToString(),"提示!");

        }

    }

    class Program

    {

        static void Main(string[] args)

        {

            Console.WriteLine("使用扩展方法显示员工信息:");

            (new User() { Name = "刘老师", Age = 28, Pay = 3000 }).Display();

        }

 }



举报

相关推荐

0 条评论