An interface can contain methods, PRoperties, events or indexers. It cannot contain fields.
1 interface IMoo2 {3 // Methods4 void Moo();5 6 // Field not allow - compile-time error7 string Name;8 }
Instead of a field, you can use a property.
1 interface IMoo2 {3 // Methods4 void Moo();5 6 // Name as a property is OK7 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
新闻热点
疑难解答