开发者

Should interfaces define properties?

开发者 https://www.devze.com 2022-12-24 11:10 出处:网络
Interfaces, as defined by MSDN \"contain only t开发者_开发百科he signatures of methods, delegates or events.\" However, since properties are no more than syntactic sugar for a get and set method, they

Interfaces, as defined by MSDN "contain only t开发者_开发百科he signatures of methods, delegates or events." However, since properties are no more than syntactic sugar for a get and set method, they are also allowed in interfaces. My question is - is there any situation where defining properties in an interface is appropriate or should we stick to the scenarios described by MSDN?


I think properties are perfectly acceptable in interfaces.

As you said, they really are a get, set, or get and set method. Many interfaces in the Framework define properties, such as IAsyncResult and IWebProxy.


The article you link to also states:

An interface can be a member of a namespace or a class and can contain signatures of the following members:

  • Methods
  • Properties
  • Indexers
  • Events


Yes, An interface should define properties when it really in need. Please suppose that. There is a IUser interface that has defined a property "Name" then you can use it without worry about if the object didn't implement the property.

public void main()
{
    IUser u = User.GetUser("id");
    string name = u.Name;
}


It is completely legitimate to define properties in interfaces. A fairly good and detailed explanation as to why you can use properties but cannot use fields is given in the answer here: Why Can's C Sharp Interfaces Contain Fields

You'll want to bear in mind that any properties defined in an interface will always be public. That is to say, if you define a getter and a setter within the interface, then both the getter and the setter must be public. You can, if you wish, define only the getter in the interface and then define a private setter in the implementing class. It's definitely an area to work carefully in.

Similarly, Java does not allow for instance variables in its interfaces. However, it does allow variables to be declared, and these will be treated as static & readonly. The convention in Java is to write getMyVariable() and setMyVariable() methods if you require them in the implementing class. C# essentially just allows for a cleaner syntax.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号