3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

RouteValueDictionaryクラスで匿名型を辞書に変換する

Last updated at Posted at 2016-06-18

匿名型のオブジェクトを受け取るメソッドを書く必要があって、objectで受け取るとプロパティにアクセスするにはリフレクション使わないといけないのかな、だとしたら面倒だなぁと思ってたら、system.web.routingにあるRouteValueDictionaryを使うと簡単にIDictionary<string, object>に変換できると知ったのでメモ。

使い方は、RouteValueDictionaryのコンストラクタに匿名型のオブジェクトを渡すだけ。簡単。

MSDN:RouteValueDictionary クラス


	using System;
	using System.Web.Routing;
	
    class Program
    {
        // 匿名型のオブジェクトを受け取り、辞書に変換する
        static void Func(object anonymousObj)
        {
            var dict = new RouteValueDictionary(anonymousObj);
            foreach (var kv in dict)
            {
                Console.WriteLine($"{kv.Key} => {kv.Value}");
            }
        }

        static void Main(string[] args)
        {
            Func(new { item1 = "aaa", item2 = 123 });
            Console.ReadLine();
        }
    }
    
3
4
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?