zoukankan      html  css  js  c++  java
  • c#之有参和无参构造函数,扩展方法

    例如在程序中创建 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)
  • 相关阅读:
    Ubuntu16安装GPU版本TensorFlow(个人笔记本电脑)
    python读取shp
    python汉字转拼音
    通过Places API Web Service获取兴趣点数据
    通过修改然后commit的方式创建自己的镜像
    centos安装postgis
    centos下mongodb备份(dump)与还原(restore)
    mysql-5.7.12安装
    Buuctf-misc-snake
    Buuctf-misc-刷新过的图片 (F5刷新)
  • 原文地址:https://www.cnblogs.com/zmztya/p/6843205.html
Copyright © 2011-2022 走看看