当前位置: 代码网 > it编程>编程语言>C# > c# base关键字的具体使用

c# base关键字的具体使用

2024年05月19日 C# 我要评论
1. 调用父类的构造函数 class father { public int age { get; set; } public string name { get;

1. 调用父类的构造函数

 	class father
    {
        public int age { get; set; }
        public string name { get; set; }
        public father(int age,string name)
        {
            this.age = age;
            this.name = name;
        }
    }
    class son:father 
    {
        public int height { get; set; }
        public son(int age,string name,int height):base (age,name)
        {
            this.height = height;
        }
    }

    class grandson : son
    {
        public grandson(int age, string name, int height) : base(age, name )
        {
            this.height = height;
        }
    }

会发现上面的代码报错,因为grandson 这个类的构造函数使用base调用父类构造函数时,提示缺少了height这个参数,这是因为base调用的只是它的父类也就是son这个类的构造函数,而不是最顶层的father这个类的构造函数,所以这里报错改成如下代码即可:

class father
{
    public int age { get; set; }
    public string name { get; set; }
    public father(int age,string name)
    {
        this.age = age;
        this.name = name;
    }
}
class son:father 
{
    public int height { get; set; }
    public son(int age,string name,int height):base (age,name)
    {
        this.height = height;
    }
}

class grandson : son
{
    public grandson(int age, string name, int height) : base(age, name,height  )
    {
        this.height = height;
    }
}

2. 调用父类的方法或者属性

 	class father
    {
        public int age { get; set; }
        public string name { get; set; }
        public father(int age, string name)
        {
            this.age = age;
            this.name = name;
        }
        public void test()
        {
            console.writeline("我是father");
        }

    }
    class son : father
    {
        public int height { get; set; }
        public son(int age, string name, int height) : base(age, name)
        {
            this.height = height;
        }
        public void test()
        {
            console.writeline("我是son");
        }
    }


    class grandson : son
    {
        public grandson(int age, string name, int height) : base(age, name, height)
        {
            this.height = height;
        }

        public void show()
        {
            int age = base.age;
            base.test();
        }
    }

调用:

grandson father = new grandson(100, "小明", 180);
father.show();

输出:

我是son

可以看出调用的方法不是father类中的test方法,而是son类,也就是grandson的父类的方法。

到此这篇关于c# base关键字的具体使用的文章就介绍到这了,更多相关c# base关键字内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com