この C コードに相当する C# を誰か教えてもらえますか?
static const value_string message_id[] = {
{0x0000, "Foo"},
{0x0001, "Bar"},
{0x0002, "Fubar"},
...
...
...
}
この C コードに相当する C# を誰か教えてもらえますか?
static const value_string message_id[] = {
{0x0000, "Foo"},
{0x0001, "Bar"},
{0x0002, "Fubar"},
...
...
...
}
public Enum MessageID { Foo = 0, Bar = 1, Fubar = 2 };
Enum.Format()
次に、またはを使用して「文字列」バージョンを取得できますToString()
。
何かのようなもの:
MessageId[] messageIds = new MessageId[] {
new MessageId(0x0000, "Foo"),
new MessageId(0x0001, "Bar"),
new MessageId(0x0002, "Fubar"),
...
};
MessageId
(適切なコンストラクターを定義する場所。)
これは C コードに最も近いものですが、tvanfosson の回答による列挙型がより適切な設計上の選択であるかどうかを確実に検討する必要があります。
private static readonly IDictionary<int, string> message_id = new Dictionary<int, string>
{
{ 0x0000, "Foo" },
{ 0x0001, "Bar" }
};
private const value_string message_id[] = {
new value_string() { prop1 = 0x0000, prop2 = "Foo"},
new value_string() { prop1 = 0x0001, prop2 = "Bar"},
new value_string() { prop1 = 0x0002, prop2 = "Fubar"},
...
...
...
}
またはさらに良いことに、辞書のように使用している場合:
private const Dictionary<string, int> message_id = {
{"Foo", 0},
{"Bar", 1},
{"Fubar", 2},
...
}
ここで、文字列は値へのキーです。
完全に一致することはありません。C# では、クラスのフィールドを許可static
しません。const
ただし、使用できますreadonly
。
これをローカル スコープで使用している場合は、匿名型入力の利点を得ることができ、次のように実行できます。
var identifierList = new[] {
new MessageIdentifier(0x0000, "Foo"),
new MessageIdentifier(0x0001, "Bar"),
new MessageIdentifier(0x0002, "Fubar"),
...
};
ただし、このソリューションの方が気に入っています。