【问题标题】:Is it possible to create properties on the fly, with a .NET dynamic object? [duplicate]是否可以使用 .NET 动态对象动态创建属性? [复制]
【发布时间】:2012-03-04 19:10:15
【问题描述】:

我正在尝试在我的 MVC 应用程序中创建一些 Json,我只想包含来自我的源对象的属性,如果它有一些属性值,请设置。

例如。

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 和 Ccccc 仅具有值: return Json(new { Aaaa = source.Aaaa, Cccc = source.Ccccc.Value };

  2. 已设置仅 Dddd。 return Json(new { Dddd = source.Dddd }

看看我是如何尝试动态创建匿名对象的。好吧,我可以这样做,因为在这个悔恨的例子中,我知道设置了什么。但是当涉及到真正的代码时,我必须“弄清楚”真正设置了什么,然后动态地返回它。

这个想法是基于Stack Exchange's Api Wrapper .. 他们有一些通过json返回的可选值,如果它们被设置的话。

【问题讨论】:

标签: c# .net asp.net-mvc dynamic


【解决方案1】:

看一下ExpandoObject,用xml的例子给出here

例如。

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

【讨论】:

猜你喜欢
  • 2012-09-22
  • 2021-08-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-01
  • 1970-01-01
  • 2012-12-09
  • 1970-01-01
相关资源
最近更新 更多