首页 > 解决方案 > 我如何在这里编写构造函数?C#

问题描述

Computer.cs
class Computer    // parent class
    {
        public string a;
        public string b;        
        public Property(string a, string b)
        {
            this.a = a;
            this.b = b;
        }
    }
Laptop.cs
class Laptop : Computer    // child class
    {
        public string y;
        public string b;        
        public Property(string y) // i dont know what comes here 
        {
            this.y = y;
        }
    }

Desktop.cs
class Desktop : Computer    // child class
    {
        public string x;    
        public string b;
        public Property(string x) // i dont know what comes here
        {
            this.x = x;
        }
    }

this.something = something <- something 是主程序中的一个变量。我不知道我必须包含在构造函数部分中的内容。

标签: c#oop

解决方案


在我看来,你正在做的这个练习是一个很好的练习,有助于学习继承是如何工作的。您的代码的修复应该是这样的:

abstract class Computer    // parent class
    {
        public string color;
        public string OwnerEmail;        
        public Computer(string color, string OwnerEmail)
        {
            this.color = color;
            this.OwnerEmail = OwnerEmail;
        }
    }

class Laptop : Computer    // child class
    {
        public string trackpadDETAILS;
        public Laptop(string trackpadDETAILS, string color, string OwnerEmail)
            : base(color, OwnerEmail)
        {
            this.trackpadDETAILS = trackpadDETAILS;
        }
    }

class Desktop : Computer    // child class
    {
        public string mouseDETAILS;        
        public Desktop(string mouseDETAILS, string color, string OwnerEmail)
            : base(color, OwnerEmail)
        {
            this.mouseDETAILS = mouseDETAILS;
        }
    }

一个工作示例在这里:https ://dotnetfiddle.net/XuhSdQ


推荐阅读