如何将任何C#对象转换为ExpandoObject? [英] How do you convert any C# object to an ExpandoObject?

查看:822
本文介绍了如何将任何C#对象转换为ExpandoObject?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了很多有关如何使用 ExpandoObject 通过添加属性从头开始动态创建对象的信息,但是我还没有发现您如何从非您已经拥有的动态C#对象.

I've read a lot about how ExpandoObject can be used to dynamically create objects from scratch by adding properties, but I haven't yet found how you do the same thing starting from a non-dynamic C# object that you already have.

例如,我有一个简单的类:

For instance, I have this trivial class:

public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Address { get; set; }
    public string Telephone { get; set; }
}

我想将其转换为ExpandoObject,以便我可以基于已有属性添加或删除属性,而不是从头开始重建相同的事物.这可能吗?

I would like to convert this to ExpandoObject so that I can add or remove properties based on what it has already, rather than rebuilding the same thing from scratch. Is this possible?

编辑:标记为重复的问题显然不是该问题的重复.

Edit: the questions marked as duplicate are clearly NOT duplicates of this one.

推荐答案

可以这样做:

var person = new Person { Id = 1, Name = "John Doe" };

var expando = new ExpandoObject();
var dictionary = (IDictionary<string, object>)expando;

foreach (var property in person.GetType().GetProperties())
    dictionary.Add(property.Name, property.GetValue(person));

这篇关于如何将任何C#对象转换为ExpandoObject?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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