Is there a way to build an Expando Object out of a non-expandoObject base class?
In other words, I am trying to do something of the sort:
// Instantiate my Expando object
dynamic myDynamicObject = new ExpandoObject();
// Add some base class to it - SomeBaseClass() can contain anything (Properties and methods)
myDynamicObject = Add SomeBaseClass(); ???
// Add some other properties that are not in the base class
myDynamicObject.Name = "My Dynamic Object";
// Add some methods
myDynamicObject.SomeMethods = (Func<bool>)(() => {
return true;
});
EDIT
As suggested by Martheen, we can construct an Expando out of another object as per this stackoverflow thread. Here is what they do:
public static dynamic ToDynamic<T>(this T obj)
{
IDictionary<string, object> expando = new ExpandoObject();
foreach (var propertyInfo in typeof(T).GetProperties())
{
var currentValue = propertyInfo.GetValue(obj);
expando.Add(propertyInfo.Name, currentValue);
}
return expando as ExpandoObject;
}
However, this example only takes care of the properties, but I also need the methods.
So I have tried to do something similar for the methods, but I don't really know what I am doing here:
public static dynamic ToDynamic<T>(this T obj)
{
IDictionary<string, object> expando = new ExpandoObject();
MethodInfo[] info = typeof(T).GetMethods();
foreach (var methodInfo in info)
{
if (methodInfo != null)
{
var currentMethod = methodInfo.GetMethodBody();
expando.Add(methodInfo.Name, currentMethod);
}
}
return expando as ExpandoObject;
}
But then when trying to execute methods I get this error:
An unhandled exception of type 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' occurred in Unknown Module.
Additional information: Cannot invoke a non-delegate type