System.IO.File.ReadLines は .NET 3.5 や mono で使えない。
だったら自分で作ってしまえ、と思ったのでやってみた。
どうでもいいけど gmcs も csc.exe と同じオプションが使えるんだね。
/out:FILENAME は -out:FILENAME みたくハイフンにするだけ。
いや、yield を使ったことが無いのでやってみようかと。
こんな強引というよりアホなメソッド追加なんてできるのかな?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | using System; using System.Collections.Generic; //IEnumerable namespace System.IO { public static partial class File { public static IEnumerable< string > ReadLines( string path) { using (var sr = new System.IO.StreamReader(path)) { string buf; while ((buf = sr.ReadLine()) != null ) { yield return buf; } } } } }</ string > |
File クラス (System.IO)
File クラスは partial class では無いみたいだけど。
コンフリクトか、やっぱりダメだった。
Windows でもやってみたけど同じ、こんなことをやろうと考えるほうがおかしい。
しかたがない、名前空間には追加できるはずだから違うクラス名にしてみる。
fakeio.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | using System; using System.Collections.Generic; //IEnumerable namespace System.IO { public static class FakeFile { public static IEnumerable< string > ReadLines( string path) { using (var sr = new System.IO.StreamReader(path)) { string buf; while ((buf = sr.ReadLine()) != null ) { yield return buf; } } } } }</ string > |
readlines.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | using System; using System.IO; class __main__ { [STAThread] public static void Main( string [] args) { if (args.Length == 0) { Console.WriteLine( "no arg..." ); return ; } int n = 0; foreach (var line in FakeFile.ReadLines(args[0])) { n++; Console.WriteLine( "{0}: {1}" , n.ToString( "000" ), line); } } } |
で、cat.exe という実行ファイルを作るコマンド。
1 | gmcs -out: cat .exe *.cs |
何故か exe という拡張子を付けないとエラーになる。
Linux でも強制するんかい、まぁ解りやすいと思えばいいし。
アスタリスクでディレクトリ内をまるごとコンパイルしてくれるのはありがたい。
なるほど、yield はこういう時に使うと確かに便利だ。
C#4.0 の ReadLines って上記を自作する以上のメリットがあるのかな?