是否可以使用.NET动态对象动态创建属性? [重复]

时间:2021-07-24 13:17:45

This question already has an answer here:

这个问题在这里已有答案:

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.

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

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 };

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

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

    Dddd只被设定了。返回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.

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

1 个解决方案

#1


11  

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

看一下ExpandoObject,这里给出了一个带xml的例子

eg.

例如。

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

#1


11  

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

看一下ExpandoObject,这里给出了一个带xml的例子

eg.

例如。

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