Is it possible to create properties on the fly, with a .NET dynamic object? [duplicate]

无人久伴 提交于 2019-12-22 04:48:10

问题


I'm trying to create a some Json in my MVC app and I only want to include the properties from my source object, if it has some properties values, set.

eg.

public class Foo
{
    public string Aaaa { get; set; }
    public string Bbbb { get; set; }
    public int? Ccccc { get; set; }
    public Lol Dddd { get; set; }
}

// Example Outputs.

  1. Aaaa and Ccccc have values only: return Json(new { Aaaa = source.Aaaa, Cccc = source.Ccccc.Value };

  2. Dddd only has been set. return Json(new { Dddd = source.Dddd }

See how i was trying to create an anonymous object on the fly. Well, I can do that because in this contrite example, I know what was set. But when it comes to real code, I would have to do 'figure out' what was really set and then dynamically return that.

The idea is based upon Stack Exchange's Api Wrapper .. where they have some optional values that they return via json, if they are set.


回答1:


Take a look at the ExpandoObject, an example with xml is given here

eg.

dynamic contact = new ExpandoObject();
contact.Name = "Patrick Hines";
contact.Phone = "206-555-0144";
... etc ...


来源:https://stackoverflow.com/questions/9259570/is-it-possible-to-create-properties-on-the-fly-with-a-net-dynamic-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!