子类看不到父方法

如何解决子类看不到父方法

我必须进行一次测试,我主要通过了MCQ部分,但是我的编码部分无法正常工作,并且由于我们的讲师不太热衷于提供反馈,因此我希望了解自己的错误并从中进行改进。解释性注释在代码中。

在Program类中,我遇到两个错误(从技术上讲三个,但一个与另一个相同)。 在带有“ Console.WriteLine(“ Commission is:”,item.CalculateComission);“的行中我得到: “ CS1061'double'不包含'CalculateComission'的定义,并且找不到扩展方法'CalculateComission'接受类型为'double'的第一个参数(您是否缺少using指令或程序集引用?)”

enter image description here

在“ GetCheapestResidance(apartments);”行中我得到: “ CS1503:参数1:无法从“ System.Collections.Generic.List ”转换为“ System.Collections.Generic.List

enter image description here

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Test2
{
    abstract class Residence
    {
        //properties Bedrooms,Bathrooms,Price
        public int Bedrooms { get; set; }

        public int Bathrooms { get; set; }

        public double Price { get; set; }

        //A no-argument constructor that creates a default Residence
        public Residence() 
        {
        
        }

        //A constructor that creates a Residence with the specified bedrooms,bathrooms,price
        public Residence(int bedrooms,int bathrooms,double price) 
        {
            Bedrooms = bedrooms;
            Bathrooms = bathrooms;
            Price = price;
        }

        //CalculateCommission() (public): abstract method with return type: double
        public abstract double CalculateCommission();
    }
}
using System;
using System.Collections.Generic;
using System.Text;

namespace Test2
{
    class Apartment : Residence
    {
        //Properties: Unit and Floor. Both are integer type 
        public int Unit { get; set; }

        public int Floor { get; set; }

        //A no-argument constructor
        public Apartment() { }

        //A constructor that creates a apartment object with the specified bedrooms,price,Unit and Floor
        public Apartment(int unit,int floor,int bedrooms,double price) : base(bedrooms,price)
        {
            Unit = unit;
            Floor = floor;
        }

        //Override CalculateCommission() method. The commission rate for an apartment is set up at 3%
        public override double CalculateCommission()
        {
            return Price * 0.03;
        }

        //toString() that returns the information about the current object
        public override string ToString()
        {
            return $" Bedrooms: {Bedrooms}\n" +
                $"Bathrooms: {Bathrooms}\n" +
                $"Floor: {Floor}\n" +
                $"Unit: {Unit}\n" +
                $"Price: {Price}";
        }
    }
}
using System;
using System.Collections.Generic;
using System.Text;

namespace Test2
{
    class House : Residence
    {
        //Propeties:  Stories and Basement.Stories is integer type,Basement is Boolean type,//indicating whether the house has basement
        public int Stories { get; set; }

        public bool Basement { get; set; }

        //A no-arg constructor
        public House() { }

        //A constructor that creates a house object with the specified bedrooms,//bathrooms,stories,basement

        public House(int stories,bool basement,price)
        {
            Stories = stories;
            Basement = basement;
        }

        //toString() that returns the information about the apartment
        public override string ToString()
        {
            return $" Bedrooms: {Bedrooms}\n" +
                $"Bathrooms: {Bathrooms}\n" +
                $"Stories: {Stories}\n" +
                $"Basement: {Basement}\n" +
                $"Price: {Price}";
        }

        //Override CalculateCommission() method. The commission rate for a house is set up at 3.5%
        public override double CalculateCommission()
        {
            return Price * 0.035;
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;

namespace Test2
{
    class Program
    {

        public static void GetCheapestResidance(List<Residence> list)
        {
            //finds the cheapest residence in the list (either in the houses list or apartments list ) 
            //depending on the parameter that you will pass. 
            var item = list.Min(x => x.Price);

            //then display the information about the cheapest residence using ToString()
            Console.WriteLine("The cheapest is: ",item.ToString());

            //and display the commission
            Console.WriteLine("Commission is: ",item.CalculateComission);
        }

        static void Main(string[] args)
        {
            List<House> houses = new List<House>();
            List<Apartment> apartments = new List<Apartment>();

            //Create three house objects  and three apartment object with data of your choice. 
            //Then add them to the the above lists.

            Residence ap1 = new Apartment(101,1,1100);
            Residence ap2 = new Apartment(102,2,1500);
            Residence ap3 = new Apartment(103,3,1900);

            Residence hs1 = new House(1,false,1500);
            Residence hs2 = new House(1,true,1900);
            Residence hs3 = new House(2,4,2300);
                        
            apartments.Add((Apartment)ap1);
            apartments.Add((Apartment)ap2);
            apartments.Add((Apartment)ap3);

            houses.Add((House)hs1);
            houses.Add((House)hs2);
            houses.Add((House)hs3);

            //Invoke GetCheapestResidance method by passing either houses list OR department list

            GetCheapestResidance(apartments);

            GetCheapestResidance(houses);

            Console.ReadKey();
        }
    }
}

解决方法

要回答第一个问题,请注意错误的措辞:“ CS1061'double'不包含'CalculateComission'的定义”。该错误表明您有一个类型为double的变量,您正在尝试对其调用CalculateComission()。错误发生在这里:

var item = list.Min(x => x.Price);
Console.WriteLine("Commission is: ",item.CalculateComission);

请注意,您没有指定item的类型,而只是说了var item。发生错误是因为Min函数返回给它的最小值。在这种情况下,您要给该功能提供价格清单。因此,item变量实际上是double类型,而不是Residence类型。因此,您正在尝试拨打电话号码CalculateCommission(),而不是在住宅电话上拨打电话。

要回答第二个问题,您不能仅将List<Apartment>用作List<Residence>。请注意以下固定代码:

//a list of residences instead of a list of apartments
List<Residence> apartments = new List<Residence>(); 

//Because Apartment is a Residence,you can make these variables Apartment or Residence
Apartment ap1 = new Apartment(101,1,1100); 
Residence ap2 = new Apartment(102,2,1500);
Apartment ap3 = new Apartment(103,3,1900);

apartments.Add(ap1);
apartments.Add(ap2);
apartments.Add(ap3);

//This time the function call is valid because GetCheapestResidance() expects a                 
List<Residence>
//and that is what we are passing in
GetCheapestResidance(apartments);

由于您的Apartment类扩展了Residence,因此您可以简单地创建一个List<Residence>作为您的公寓列表,并像往常一样将公寓添加到其中。这应该解决将List<Apartment>传递到期望List<Residence>的函数中的问题。

,

所有好的问题。

我一次要经历一个:

  1. 双精度型错误是因为您的var item = list.Min(...在遍历列表后返回了最小值。它返回找到的价格的最小值,而不是拥有该值的对象的价格。

    要解决此问题,您可以使用.Aggregate函数。这有点复杂,所以我建议您看一下这篇文章以获取更多详细信息:How to use LINQ to select object with minimum or maximum property value 。您可以执行此操作的另一种方法是使用简单的for或foreach循环,并在迭代过程中跟踪最小值及其所有者。

  2. 此方法GetCheapestResidence抱怨的原因是,它需要一个Residences列表,而您提供一个Apartments列表。不幸的是,您不能将这些列表相互区分,我认为这是列表的限制(如果有人知道为什么,请在下面发表评论)。因此,您必须在此处提供正确的列表类型。您已经创建了Residences引用的新公寓,那么为什么不将这些Residences合并到自己的列表中呢?

         List<House> houses = new List<House>();
         List<Residence> apartments = new List<Residence>();
    
         //Create three house objects  and three apartment object with data of your choice. 
         //Then add them to the the above lists.
    
         Residence ap1 = new Apartment(101,1100);
         Residence ap2 = new Apartment(102,1500);
         Residence ap3 = new Apartment(103,1900);
    
         Residence hs1 = new House(1,false,1500);
         Residence hs2 = new House(1,true,1900);
         Residence hs3 = new House(2,4,2300);
    
         apartments.Add(ap1);
         apartments.Add(ap2);
         apartments.Add(ap3);
    
         houses.Add((House)hs1);
         houses.Add((House)hs2);
         houses.Add((House)hs3);
    
         //Invoke GetCheapestResidance method by passing either houses list OR department list
    
         GetCheapestResidance(apartments);
    

在这里,我已将您的列表更改为列表,就像您当前的代码一样,您没有使用任何公寓列表。房屋也一样。

如果有人对此有更好的解决方案,请随时评论或编辑。

,

对于第一个错误,请尝试使用+而不是逗号来连接参数,并在item.CalculateCommision()的末尾添加括号以实际获得函数的结果。但是主要的问题是您要在double而不是对象上调用函数。您可以更改Min通话,以进行类似list.OrderBy(x => x.Price).FirstOrDefault()的操作,以最低的价格获得住所并退还。 对于第二个错误,请尝试从公寓列表更改为居民列表,以查看是否有帮助。该参数不接受您要传递的类型,但是您应该能够将公寓实例添加到住宅列表中。

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

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-