Convert class to dynamic and add properties

后端 未结 5 1852
庸人自扰
庸人自扰 2020-12-04 01:53

I have a class MyClass. I would like to convert this to a dynamic object so I can add a property.

This is what I had hoped for:

dynamic          


        
5条回答
  •  青春惊慌失措
    2020-12-04 02:16

    The following has worked for me in the past:
    It allows you to convert any object to an Expando object.

    public static dynamic ToDynamic(this T obj)
    {
        IDictionary expando = new ExpandoObject();
    
        foreach (var propertyInfo in typeof(T).GetProperties())
        {
            var currentValue = propertyInfo.GetValue(obj);
            expando.Add(propertyInfo.Name, currentValue);
        }
        return expando as ExpandoObject;
    }
    

    Based on: http://geekswithblogs.net/Nettuce/archive/2012/06/02/convert-dynamic-to-type-and-convert-type-to-dynamic.aspx

提交回复
热议问题