在C#中学习OOP规则的最佳方法或最佳实践 [英] best way or best-practices for learning OOP rules in c#

查看:89
本文介绍了在C#中学习OOP规则的最佳方法或最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现C#非常有趣...但是(或幸运的是!)它具有实现OOP规则的许多功能....它们具有不同的机制,有时会使我感到困惑....

I found C# very interesting...but unfortunately (or fortunately ! ) it has many features to implement OOP rules....they have different machanisms and make me sometimes confused....

c#中的虚拟,新,...修饰符具有不同的规则..那么学习OOP规则并轻松使用它们的最佳方法或最佳实践是什么?

virtual, new,... modifiers in c# have different rules....so what is the best way or best-practices for learning OOP rules and use them easily...?

那么学习OOP规则并轻松使用它们的最佳方法是什么?

so what is the best way or best-practices for learning OOP rules and use them easily...?

推荐答案

最好的学习方法是使事情保持简单,并经常练习(编程). 关于虚拟/新/覆盖,主要有以下三种情况:

The best way to learn is to keep things simple and practice (program) a lot. Regarding virtual/new/override, there are three main cases:

  1. 虚拟+覆盖-在基类中使用virtual并在派生类中覆盖,如:

  1. Virtual + override - Use virtual in the base class and override in the derived class, as in:

class BaseClass  
{      
     public void virtual Test(){...}  
}  
class DerivedClass: BaseClass  
{  
    public void override Test(){...}  
}

  • 抽象+覆盖-这是先前情况的变体,其中基础成员未定义主体:

  • Abstract + override - This is a variant of the previous case where the base member does not define a body:

    abstract class BaseClass
    {
        public void abstract Test(){...}
    }
    class DerivedClass: BaseClass
    {
        public void override Test(){...}
    }
    

  • 无修饰符-当您不打算覆盖方法时,这很有用:

  • No modifier - This is useful when you don't plan on overriding a method:

    class BaseClass
    {
        public void Test(){...}
    }
    class DerivedClass: BaseClass
    {
        public void OtherMethod(){...}
    }
    

    在这种情况下,如果OtherMethod被命名为Test,则会出现警告.确实,它将与基本方法冲突.您可以通过添加

    In the this case, there would be a warning if OtherMethod was named Test. Indeed, it would clash with the base method. You can get rid of the warning by adding a new modifier as in

    abstract class BaseClass
    {
        public void Test(){...}
    }
    class DerivedClass: BaseClass
    {
        public new void Test(){...}
    }
    

    但是,我建议尽可能避免使用new修饰符,因为它有些令人困惑.

    However, I would recommend avoiding the new modifier if possible since it is somewhat confusing.

    这篇关于在C#中学习OOP规则的最佳方法或最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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