如何将任何C#对象转换为ExpandoObject?

如何将任何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));