• C#抽象类可以有构造方法吗,若是有如何实现及调用?


    抽象类可以有构造函数吗?--可以有,若是不写,提供默认protected级别构造.
    如果有,其带参构造和无参构造什么时候,怎样调用?--无参构造自动调用,带餐构造必须显式调用,和是否抽象类无关.

    /*--===------------------------------------------===---
    作者:许明会
    日期:2008年1月18日 16:33:57
    目的:抽象类中可以有构造函数吗? 如何调用?

    若希望类能够有派生类,必须为其实现默认构造函数.
    若类没有实现带餐构造,编译器将自动创建默认构造函数.
    若类实现了带参构造,则编译器不会自动生成默认构造.

    子类实例化时(不管是否为带参构造):
        只会调用所有父类的无参构造函数
        带参构造必须通过显式去调用.
    --===------------------------------------------===---
    */

    using System;

    namespace xumh
    {
        
    public abstract class myClass
        
    {
            
    //总会被调用,否则无法创建带参构造
            public myClass()
            
    {
                Console.WriteLine(
    "抽象类中的无参构造函数.");
            }

            
    //只可以显式调用
            public myClass(int a, int b)
            
    {
                Console.WriteLine(
    "抽象类中的带参构造函数:{0},{1}.",a,b);
            }

        }

        
        
    public class test : myClass
        
    {
            
    public test()
            
    {
                Console.WriteLine(
    "派生类中的无参构造函数.");
            }

            
    public test(int a, int b)//:base(a,b)//显式调用
            {
                Console.WriteLine(
    "派生类中的带参构造函数:{0},{1}.",a,b);
            }

        }


        
    public class runMyApp
        
    {
            
    static void Main()
            
    {
                test t1 
    = new test();
                test t2 
    = new test(1,2);
            }

        }

    }

    /*--===------------------------------------------===---
    输出信息如下:
    抽象类中的无参构造函数.
    派生类中的无参构造函数.
    抽象类中的无参构造函数.
    派生类中的带参构造函数:1,2.
    --===------------------------------------------===---
    */
  • 相关阅读:
    MySQL 存储过程
    linux iptables 相关设置
    Ubuntu iptables 设置
    Mac OS 10.12
    解决:cc1.exe: sorry, unimplemented: 64-bit mode not compiled in
    go get golang.org/x/net 安装失败的解决方法!
    Ubuntu16.04
    Ubuntu16.04
    Ubuntu16.04
    在Ubuntu16.04里面安装Gogland!
  • 原文地址:https://www.cnblogs.com/ccky/p/1349530.html
Copyright © 2020-2023  润新知