I have a DynamicObject
and I want it to be castable to IDictionary, exactly the same way as ExpandoObject
. For example, casting an ExpandoObject to IDictionary is perfectly valid:
dynamic ex = new ExpandoObject ();
ex.Field = "Foobar";
IDictionary<string, object> dict = ex as IDictionary<string, object>;
Console.WriteLine (dict["Field"]);
Now I try to implement this into my own DynamicObject:
public class MyDynamicObject : DynamicObject
{
public Dictionary<string, object> members = new Dictionary<string, object> ();
public override bool TryGetMember (GetMemberBinder binder, out object result)
{
if (members.ContainsKey (binder.Name)) {
result = members[binder.Name];
return true;
}
else {
result = null;
return false;
}
}
public override bool TrySetMember (SetMemberBinder binder, object value)
{
this.members.Add (binder.Name, value);
return true;
}
public static implicit operator IDictionary<string, object> (MyDynamicObject mydo)
{
return (IDictionary<string, object>) mydo.members;
}
}
But the compiler will fail on the public static implicit operator IDictionary<string, object>
line, giving the error: "Cannot convert to or from an interface type". If I change the implicit operator to Dictionary, I can cast MyDynamicObject to Dictionary without any Problems, but not IDictionary.
How does ExpandoObject does this?