代码如下:
interface Interface1
{ string name; void ttt();}
编译会抱错:Interfaces cannot contain fields.
可见,c#接口里不能有字段field。
那这种需求如何解决呢?
查一下msdn即知接口可以包含的成员如下:
Methods
Properties
Indexers
Events
也就是说,c#可以有属性,它是字段的安全升级版。
代码如下,仅仅在name后加个大括号,敲进去get,set之一即可。
interface Interface1
{ string name { get; } void ttt();}
在实现这个接口的类中,除了要给属性方法显示手动的加上public外,
class Class1 : Interface1
{ public string name { get { return "abc"; } }public void ttt()
{ } }
Using Properties (C# Programming Guide)
interface (C# Reference)