Casting anonymous type to dynamic

后端 未结 5 1229
渐次进展
渐次进展 2020-12-14 06:06

I have a function that returns an anonymous type which I want to test in my MVC controller.

public JsonResult Foo()
{
    var data = new
                  {
         


        
5条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-14 06:26

    Anonymous type is a regular static type in .NET, it's just that you do not give it a name (a compiler, however, does). That's why casting it to dynamic will not work. However, if you have control over Foo(), you can construct and return a dynamic object instead of anonymous, and then your code is going to work. This should do the trick:

    dynamic JsonResult Foo() {
        dynamic data = new ExpandoObject();
        data.details = "something";
        data.mode = "More";
        return Json(data);
    }
    

提交回复
热议问题