Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
开发者_如何学PythonClosed 7 years ago.
Improve this questionWhen writing a method that takes a string and populates a poco based on it, is it better to have a static Parse(string s)
method like Int32.Parse()
or overload the constructor so it takes a string?
I prefer the constructor version, but including both is easy, since the constructor can just call Parse
. This is the pattern followed by the Guid
struct (and likely others as well.)
I should add that if you're not dealing with a struct
, then the static
method should probably be referring to the constructor (or even a separate method that both can call) since you can't assign to this
in a class
constructor.
EDIT: As TrueWill points out, if you do include Parse
, you should include TryParse
as well. Incidentally, Guid
is once again instructive: the Parse
method actually uses TryParse
, and just throws an exception if TryParse
returns false
.
If the method might fail due to an invalid string, I'd lean towards Parse and include TryParse as per the TryParse pattern.
I would recommend using .Parse(string s) if its a simple object, if the object stores more then 1-2 values you should use the constructor, or in other words, dont parse if the return value will be an instance with memebers unaffected by the parse value.
精彩评论