首页 > 解决方案 > 在类中使用 ASP.Net Core 2.1 与 ASP.Net 4.1 MVC 的继承和实例化问题

问题描述

这两个类都在不同的类文件中,但在同一个文件夹中。这是我的代码。

public class Person
{
    public String FirstName { get; set; }
    public String LastName { get; set; }
    public String Email { get; set; }
    public DateTime DateOfBirth { get; set; }
}

public class Zodiac : Person
{
   public Zodiac()
   {
      //person.DateOfBirth = DateTime.Now;
      DateOfBirth = DateTime.Now;// this doesn't work either
   }
      //Person person = new Person();
 }

即使我使用实例化,即使它们在同一个文件夹中也不起作用。它给了我这个错误。

严重性代码 描述 项目文件行抑制状态错误 CS0103 当前上下文中不存在名称“DateOfBirth” PersonExercise D:\Exercises\PersonExercise\PersonExercise\Models\Zodiac.cs 12 活动

如果我使用实例化,它会给我这个错误。

严重性代码描述项目文件行抑制状态错误 CS1061“Person”不包含“DateOfBirth”的定义,并且找不到接受“Person”类型的第一个参数的可访问扩展方法“DateOfBirth”(您是否缺少 using 指令或程序集参考?)PersonExercise D:\Exercises\PersonExercise\PersonExercise\Models\Zodiac.cs 12 Active

以下是有关该问题的屏幕截图:

使用继承

使用实例

标签: c#asp.net-mvcasp.net-core-2.1

解决方案


看起来像一些错字+不完全理解继承。检查以下代码中的注释。

public class Zodiac : Person
{
    public Zodiac()
    {
      person.DateOfBirth = DateTime.Now; // This would not work, you have not declared an object named "person", note it is commented.
      DateOfBirth = Datetime.Now;// this doesn't work. <-- Indeed, there is a typo
      DateOfBirth = DateTime.Now;// this would work, note the uppercase Time.
    }
    //Person person = new Person();
}

推荐阅读