开发者

Can I return a StreamReader from a method?

Can I return a StreamReader from开发者_运维知识库 a method ?


Yes, of course. It's not a great idea, though - you're creating the StreamReader in one method, and closing it in another. It's better practice to create and close the reader in one method.


Sure. Using normal IDispose semantics, here is how it would look:

  StreamReader MakeStreamReader () {
     return new StreamReader ("somefile.txt");
  }

  void Caller () {
     using (StreamReader r = MakeStreamReader ()) 
        Console.WriteLine (r.ReadToEnd ());
  }
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜