What should the out value be set to with an unsuccessfull TryXX() method?

谁说胖子不能爱 提交于 2019-12-24 01:44:26

问题


I'm implementing a TryParse(string s, Out object result) method. If the parse fails, I would like not to touch the out parameter so any previous result will remain intact. But VS2k8 won't let me. I have to set the value of the out object no matter what.

Should I just put result = result for the sake of pleasing the compiler? Am I missing something?


回答1:


Your suggestion of result = result won't work, because it's an out parameter - it's not definitely assigned to start with, so you can't read its value until you've assigned a value to it.

result = null;

is definitely the right way to go for an object out parameter. Basically use default(T) for whatever type T you've got. (The default operator is useful in generic methods - for non-generic code I'd normally just use null, 0, whatever.)

EDIT: Based on the comment from Boris, it may be worth elaborating on the difference between a ref parameter and an out parameter:

Out parameters

  • Don't have to be definitely assigned by the caller
  • Are treated as "not definitely assigned" at the start of the method (you can't read the value without assigning it first, just like a local variable)
  • Have to be definitely assigned (by the method) before the method terminates normally (i.e. before it returns; it can throw an exception without assigning a value to the parameter)

Ref parameters

  • Do have to be definitely assigned by the caller
  • Are treated as "definitely assigned" at the start of the method (so you can read the value without assigning it first)
  • Don't have to be assigned to within the method (i.e. you can leave the parameter with its original value)



回答2:


Assign null (or default(T) more generally). You must assign a value, that's what 'out' means.




回答3:


result = null;



回答4:


Just put some default value. For example the Int32.TryParse method puts zero.




回答5:


You could use ref instead of out if you don't want to assign a value, although this must then be initialised by the caller.




回答6:


You could throw an exception before the code that is supposed to set result.



来源:https://stackoverflow.com/questions/862207/what-should-the-out-value-be-set-to-with-an-unsuccessfull-tryxx-method

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!