不知道什么时候使用抽象属性,什么时候不 [英] Not sure when to use an abstract property and when not

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

问题描述

我真的不知道有什么好看还是当我真正在抽象类和属性,或当使用非抽象的性质使用。我会尽力做一个简单的例子。比方说,我有这样的:

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
}

这是好吗?我的理解,我没有用一个抽象的财产,如果我不想覆盖它。而在这种情况下,这将是确定的,就像方法讲睡眠等应该是抽象的。

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.

使用的覆盖关键字重写的成员。马克成员为封控,如果它不应该被再次改写。

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

不要标记属性作为摘要虚拟如果你不希望它被覆盖做。

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

使用关键字隐藏非抽象,非虚成员(这很少是个好主意)。

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.

请参阅:

  • Should Properties have Side Effects
  • CA1024: Use properties where appropriate

就个人而言,我发现我使用抽象方法频繁,但抽象属性很少。

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

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

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