码迷,mamicode.com
首页 > Windows程序 > 详细

c#之有参和无参构造函数,扩展方法

时间:2017-05-12 00:13:53      阅读:460      评论:0      收藏:0      [点我收藏+]

标签:blog   nbsp   ram   stat   code   自身   方法   test   ase   

例如在程序中创建 Parent类和Test类,在Test有三个构造函数,parent类继承Test类,那么我们可以在Test类自身中添加 扩展 方法吗?

答案:是不可以的。因为扩展方法必须是静态的,且静态方法是不存在构造函数的。

先看一段代码:

public class Test
    {
        public Test()
        {
            Console.WriteLine("这是无参的构造函数");    
        }
        public Test(string name)
        {
            Console.WriteLine(string.Format("这是有参的构造函数,想知道name:{0}",name));
        }
        public Test(Test test, int age)
        {
            Console.WriteLine("这是含有Test类型的函数");
        }
    }




public class Parent:Test
    {
        public Parent() : base(new Test(), 11) {
            Console.WriteLine("调用Test中的有参构造函数");
        }

    }



class Program
    {
        static void Main(string[] args)
        {

            Parent parent = new Parent();
           //在调用的时候时候,是先调用了Test中的无参构造函数,接着调用了有Test类行的有参构造函数
        }
    }

还有一个this()的用法:

public class aaa{
      public aaa(int v){}
      public aaa() :this(11) {}   
}

那么如何实现扩展呢?

public static class HasKz
    {
        public static void getName(this HasKz kz, int age)
        {
         //报错,提示静态类不能作为参数
        }
   }
//得到的结论,自身类中不能实现扩展方法

//同时扩展方法是在静态中定义的

例如在parent正确的定义//public static void GetName(this Test t,int name)

 

c#之有参和无参构造函数,扩展方法

标签:blog   nbsp   ram   stat   code   自身   方法   test   ase   

原文地址:http://www.cnblogs.com/zmztya/p/6843205.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!