简体   繁体   中英

C# specifying difference between parent class vs interface

In C# you specify the parent class for inheritance the same way you specify an interface with the ":" after the class definition

public class MyClass : ParentClass

public class MyClass : SimpleInterface

So, how can you tell when the item after the colon is a parent class vs an interface?

The rule is to start names of interfaces with a capital I and the first letter of the name after the I also a capital letter: IDictionary , IList . This pattern is easy to recognize and should be followed.

Furthermore:

  • A class can have only one base class, but implement multiple interfaces. Everything after a comma is necessarily an interface: class Subclass : Baseclass, IInterface1, IInterface2
  • Interface identifiers are colored differently in most modern IDEs
  • Most modern IDEs provide this information on mouse hover or with a "goto definition" command

Regarding the "specifying difference" in the question title, this is specified in the declaration. Even if you deviate from the naming conventions, you cannot have an interface and a class or struct of the same name in the same namespace. There is no need to make a distinction by syntax in the inheritance list of a class declaration.

Click on the name after the : then press F12 . VS will jump to the declaration of it. If you read in the declaration the word interface then your suspect is an interface. Otherwise it will be a class

除了建议的以外,您可以使用IsInterface属性,例如

typeof(MyClass).BaseType.IsInterface

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM