匿名クラスをDictionaryなどのコレクションから動的に作成する方法を説明します。
環境(バージョン)
.NETのバージョン
% dotnet --version 5.0.101
本題
匿名型(匿名クラス)を動的に作成するには、System.Dynamic.ExpandoObjectクラスを使用します。サンプルプログラムです。
using System;
using System.Dynamic;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
// 動的に作成するプロパティ、値の組み合わせをDictionaryに登録
var dic = new Dictionary<string, string>();
dic.Add("key1", "キー1");
dic.Add("key2", "キー2");
// 匿名型をDictionaryから作成
dynamic anonymousType = new ExpandoObject();
foreach (var item in dic)
{
((IDictionary<string, object>)anonymousType).Add(item.Key, item.Value);
}
// 以下の匿名型と同じ
var test = new { key1 = "キー1", key2 = "キー2" };
Console.WriteLine(anonymousType.key1); // キー1
Console.WriteLine(anonymousType.key2); // キー2
Console.WriteLine(test.key1); // キー1
Console.WriteLine(test.key2); // キー2
}
}


コメント