#443 - An Interface Cannot Contain Fields

An interface can contain methods, properties, events or indexers. It cannot contain fields.

1 interface IMoo

2 {

3     // Methods

4     void Moo();

5 

6     // Field not allow - compile-time error

7     string Name;

8 }

Instead of a field, you can use a property.

1 interface IMoo

2 {

3      // Methods

4      void Moo();

5  

6      // Name as a property is OK

7      string Name{get; set;}

8 }

Interfaces don't allow fields because they consist of a constract that is a list of methods, whose implementation is provided by a class. Properties are implemented as methods (get and set accessors), so they fit this model. But fields are just data locations, so it doesn't make sense to include them in an interface.

原文地址:#443 - An Interface Cannot Contain Fields

你可能感兴趣的:(interface)