When should I write Static Methods?

后端 未结 8 805
梦如初夏
梦如初夏 2021-01-04 02:31

So I understand what a static method or field is, I am just wondering when to use them. That is, when writing code what design lends itself to using static methods and field

8条回答
  •  情歌与酒
    2021-01-04 03:12

    It gives a better idea of the intent when you use a static factory -- it also lets you have different factories that take the same argument types but have a different meaning. For example, imagine if Bitmap had LoadFromResource(string) -- it would not be possible to have two constructors that both took string.

    EDIT: From stevemegson in the comments

    A static factory can also return null, and can more easily return an instance that it got from cache. Many of my classes have a static FromId(int) to get an instance from a primary key, returning an existing cached instance if we have one.

提交回复
热议问题