2008-06-20 Fri
■ UPnPデバイスの列挙 [C#]
2008-06-14-1 の C# 版
CoInitialize を書かない。
CoCreateInstance の代わりに new を使う。
BSTR は string
UPnPDevices を foreach でくるくる。
IUnknown.Release の代わりに Marshal.ReleaseComObject を使う。
using System; using System.Collections; using System.Runtime.InteropServices; using UPNPLib; namespace upnp_enum_dev { class Program { static void Main(string[] args) { ArrayList rcws = new ArrayList(); try { UPnPDeviceFinder df = new UPnPDeviceFinder(); rcws.Add(df); UPnPDevices ds = df.FindByType("upnp:rootdevice", 0); rcws.Add(ds); foreach (UPnPDevice d in ds) { rcws.Add(d); Console.WriteLine(d.FriendlyName); } } finally { foreach(object obj in rcws) { try { Marshal.ReleaseComObject(obj); } catch { } } } } } }
リソースの解放は D言語の scope(exit) のほうが見やすい。
2007-12-17 Mon
■ using [C#]
using 文は D言語の scope(exit) 文に似た機能を持っている。
C# 言語仕様の208ページにから引用
using System; using System.IO; class Test { static void Main() { using (TextWriter w = File.CreateText("log.txt")) { w.WriteLine("This is line one"); w.WriteLine("This is line two"); } using (TextReader r = File.OpenText("log.txt")) { string s; while ((s = r.ReadLine()) != null) { Console.WriteLine(s); } } } }
これを D言語 で書くと、
void main(){ { File w = new File("log.txt",FileMode.Out); scope(exit) w.close(); w.writeLine("This is line one"); w.writeLine("This is line two"); } { File r = new File("log.txt",FileMode.In); scope(exit) r.close; char[] s; while ((s =r.readLine()) != "") { writefln(s); } }
こんな感じだろうか?
finally を書かなくてすむ。
2007-12-17 Mon
■ 怖いものを見た [C#]
Windows の API に UPnP が用意されている。
COM になっている。
C# から扱う方法を探してみる。
try finally のネストがすごい。
boost::intrusive_ptr みんたいなのがほしい。
COM Interop, Marshal.ReleaseComObject
C++ でつくるかな
2007-12-15 Sat
■ string型をbyte配列に入れるには [C#]
static void Main() { string message = "hello world"; byte[] buffer = Array.ConvertAll(message.ToCharArray(),new Converter<char,byte>(CharToByte)); } static CharToByte(char c) { return Convert.ToByte(c); }
これでできた。
ConvertAll の第2引数を匿名メソッドにできそうな気がする。
new Converter<char, byte>(delegate (char c){return Convert.ToByte(c);})
こうか。
もっと簡単な方法があるだろうか?。
2007-12-15 Sat
■ C# 言語仕様 [C#]
1.2 仕様では、Visual C# 2005 より前に言語に追加された機能について説明し、2.0 仕様では、Visual C# 2005 に追加された機能について説明しています。
C# 言語仕様は、Microsoft Word 形式で次の場所から入手できます。
MSDN オンラインの Visual C# Developer Center
Visual Studio (Microsoft Visual Studio 2005 インストール ディレクトリの VC#\Specifications\1033\ ディレクトリ)
C# のコンパイル方法
アプリケーション
csc application.cs
ライブラリ
csc /t:liblary liblary.cs
ライブラリを使用したアプリケーション
csc /r:liblary.dll application.cs
規約により、静的メソッド Main は、プログラムのエントリ ポイントとして機能します。
C# でのエントリポイントは、main 関数でない。
静的な Main メソッドがエントリポイントになる。
static void Main(){...} static void Main(string[] args){...} static int Main(){...} static int Main(string[] args){,,,}
型
値型
- 単純型
- 列挙方
- 構造体
参照型
- クラス型
- インターフェース型
- 配列型
- デリゲート型
ボックス化
値型は object型に、入れられる。
戻すときはキャストする。
メソッド
C# では、すべてのメソッドは、クラスまたは構造体のメンバとして定義されている必要があります。