【问题标题】:Should the debugger throw some warning when passing a derived class as a parameter?将派生类作为参数传递时,调试器是否应该抛出一些警告?
【发布时间】:2018-10-31 10:59:49
【问题描述】:

我正在研究 ASP.NET Core,我发现了一个关于继承的事物(因为 IdentityUser 可以由 ApplicationUser 派生)。

这里只是一个演示来解释它是什么:

实体:

public class Animal
{
    public string Name { get; set; }
}

public class Cat : Animal
{
    // cat has no wings...
}

public class Eagle : Animal
{
    public object LeftWing { get; set; }
    public object RightWing { get; set; }
}

数据库上下文(仅用于演示):

public void SaveChanges(Animal animal)
{
    // save changes for "Animals" table...
}

并使用它:

var cat = new Cat { Name = "Norris" };
var eagle = new Eagle { Name = "Voldemort", LeftWing = "good", RightWing = "broken" };

SaveChanges(cat);
SaveChanges(eagle);

// in asp.net core, this can be:
// public class ApplicationUser : IdentityUser {}

// _dbContext.Users.Add(new ApplicationUser { ExtensionProperty = "foo" });

// but we forgot to update the "Users" table 
// which refers to "ApplicationUser" class instead if "IdentityUser" class by default
// _dbContext.Users.Add(new IdentityUser());

由于猫没有翅膀,我们不需要添加左翼和右翼作为两个属性。

另外,并不是所有的动物都有翅膀,所以不需要在表格Animals中定义。

为了解决这个问题,我们可以创建两个表CatsEagles

但在这篇文章中,我只想提到继承。

当儿子有2个翅膀而爸爸没有时,什么时候可以用儿子代替爸爸?

【问题讨论】:

  • 您是在询问每个类型的表与每个层次结构的表吗?用关键字实体框架搜索那些,那里有足够的材料来回答你的问题(我认为)。如果不改写你的问题,因为你根本不清楚你在问什么(无论如何对我来说)。
  • @Igor 哦。对不起。我的意思是,当我尝试使用表中未定义的一些扩展属性更新数据库时。调试器不会对此发出任何警告。这仍然是一个有效的操作。

标签: c# inheritance visual-studio-code vscode-debugger


【解决方案1】:

不,不应该。你已经说过你的方法只需要一个“动物”就可以了。

如果您需要了解关于翅膀等的信息,那么您的合同是否有误?

在这种情况下,也许动物就足够了,让 ORM(例如实体框架)解决如何持久化它(即在单独的表中)。

【讨论】:

  • then perhaps your contract is wrong?。是的,你知道我的意思,谢谢!但由于CatEagle 派生到Animal,因此我没有收到任何警告/错误消息,因为继承。
  • 我不希望你收到警告!您选择 Animal 作为您的方法参数类型。你的方法应该适用于动物!如果没有,那么您需要更改您的方法签名。通过将动物添加到签名中,您已形成合同并向消费者声明您可以处理所有衍生动物。
猜你喜欢
  • 2011-06-03
  • 2017-08-14
  • 2011-05-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多