是否有可能在飞行中创建属性,用.NET动态对象? [英] Is it possible to create properties on the fly, with a .NET dynamic object?

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

问题描述

我想在我的MVC应用程序创建一些JSON和我只是想从我的源对象包括的属性,如果它有一些属性值设置。

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.

如:

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

//例输出。

  1. AAAA级和CCCCC只值: 返回JSON(新{AAAA级= source.Aaaa,CCCC = source.Ccccc.Value};

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

DDDD唯一还没有确定。 返回JSON(新{DDDD = source.Dddd}

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

看我怎么试图动态创建一个匿名对象。好吧,我能做到这一点,因为在这种懊悔的例子,我知道发生了什么设置。但是,当涉及到实际code,我会做弄清楚什么是真正集,然后动态地返回。

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.

我们的想法是基于堆栈交易所的API包装 ..他们在那里,他们通过JSON返回一些可选值,如果它们被设定

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.

推荐答案

看看的的 ExpandoObject ,使用XML给出一个例子<一个href="http://blogs.msdn.com/b/csharpfaq/archive/2009/10/01/dynamic-in-c-4-0-introducing-the-expandoobject.aspx">here

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

如:

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

这篇关于是否有可能在飞行中创建属性,用.NET动态对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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