【问题标题】:How do I write the constructor here? C# [closed]我如何在这里编写构造函数? C# [关闭]
【发布时间】:2021-05-25 13:32:39
【问题描述】:
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

【问题讨论】:

  • 也许你需要了解一下constructors“构造函数是一种方法,其名称与其类型的名称相同” - 不确定是否是问题所在。

标签: c# oop


【解决方案1】:

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

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

【讨论】:

  • 如果我要调用它,我将如何在主循环中调用它。我将所有详细信息添加到列表中。这个对吗? """ Computer.Add(new Laptop or Desktop(trackpaddetails or mousedetails, color, owneremail))""".
  • 好的,我在这里添加一个使用示例:dotnetfiddle.net/XuhSdQ
  • 有没有办法可以显示我列表中的所有数据?因为我有 2 种不同类型的对象,所以我无法为每个循环选择要显示的 mousedetails 和 trackpaddetails。当我使用 console.writeline 时,我只能显示父类字段,如颜色和 owneremail。
  • @user14186716 您需要将它们转换为正确的类型。喜欢这里:dotnetfiddle.net/8ZxpzL
猜你喜欢
  • 2017-03-26
  • 2017-10-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-03
  • 1970-01-01
  • 1970-01-01
  • 2014-03-31
相关资源
最近更新 更多