不确定何时使用抽象属性,何时不使用 [英] Not sure when to use an abstract property and when not

查看:33
本文介绍了不确定何时使用抽象属性,何时不使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不确定什么看起来更好,或者我什么时候真正在抽象类和属性中使用,或者什么时候使用非抽象属性.我会尝试做一个简单的例子.假设我有这个:

I'm not really sure what looks better or when do I really use in abstract classes and properties, or when to use non abstract properties. I'll try to make a simple example. Let's say I have this:

abstract class Human
{
  public GenderType Gender { get; set; }
  public string Name { get; set; }
  public Date Born { get; set; }
  public bool IsNerd { get; set; }

  abstract public void Speak();
  abstract public void Sleep();
  abstract public void AnoyingPeopleOnStackOverflow();
  //... so on
}

class Peter : Human
{
  //Peter is special, he got a second name
  //But thats all, everything else is the same as like on other humans
  public string SecondName { get; set; }

  //...override abstract stuff
}

这样好吗?据我了解,如果我不想覆盖它,我不必使用抽象属性.在这种情况下就可以了,只是像 SpeakSleep 等方法应该是抽象的.

Is this alright? As I understood, I don't have to use an abstract property if I dont want to override it. And in this situation it would be ok, just the methods like Speak, Sleep and so on should be abstract.

现在,如果这没问题,我什么时候会或应该使用抽象属性?

Now, if this is ok, when would or should I use an abstract property?

推荐答案

当您没有默认实现并且派生类必须实现它时,请使用抽象属性.

Use an abstract property when you have no default implementation and when derived classes must implement it.

当您在基类中有实现但希望允许覆盖时,请使用虚拟属性.

Use a virtual property when you have an implementation in the base class but want to allow overriding.

使用 override 关键字来覆盖成员.如果不应再次覆盖该成员,请将其标记为 密封覆盖.

Use the override keyword to override a member. Mark the member as sealed override if it should not be overridden again.

如果您不想覆盖该属性,请不要将其标记为 abstractvirtual.

Don't mark the property as abstract or virtual if you don't want it to be overridden.

使用 new 关键字来隐藏非抽象、非虚拟成员(这很少是一个好主意).

Use the new keyword to hide a non-abstract, non-virtual member (this is rarely a good idea).

如何:定义抽象属性

我发现抽象属性经常出现在设计中,这意味着它们将具有特定于类型的逻辑和/或副作用.您基本上是在说,这是所有子类都必须具有的数据点,但我不知道如何实现它".然而,包含大量逻辑和/或引起副作用的属性可能是不可取的.这是一个重要的考虑因素,尽管没有固定的正确/错误方法.

I find that abstract properties often occur in a design which implies that they will have type-specific logic and/or side effects. You are basically saying, "here is a data point that all subclasses must have, but I don't know how to implement it". However, properties which contain a large amount of logic and/or cause side effects may not be desirable. This is an important consideration, though there is no fixed right/wrong way to do it.

见:

就我个人而言,我发现我经常使用抽象方法,但很少使用抽象属性.

Personally, I find that I use abstract methods frequently but abstract properties rarely.

这篇关于不确定何时使用抽象属性,何时不使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆