使用.NET动态对象可以即时创建属性吗? [英] Is it possible to create properties on the fly, with a .NET dynamic object?

查看:93
本文介绍了使用.NET动态对象可以即时创建属性吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



例如

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

//输出示例


  1. Aaaa和Ccccc只有值:
    return Json(new { Aaaa = source.Aaaa,Cccc = source.Ccccc.Value};


  2. 只有Dddd已设置
    return Json(new {Dddd = source.Dddd}


看看我是如何试图在飞行中创建一个匿名对象,那么我可以这样做,因为在这个讽刺的例子中,我知道已经设置了什么,但是当涉及到真实的代码时,我将不得不弄清楚什么是真正设置,然后动态地返回。



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

解决方案

p>看看 ExpandoObject ,给出了一个带有xml的示例 here



eg。

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


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.

解决方案

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 ...

这篇关于使用.NET动态对象可以即时创建属性吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆