我有一个DynamicObject
并且我希望它可以转换为 IDictionary,与ExpandoObject
. 例如,将 ExpandoObject 强制转换为 IDictionary 是完全有效的:
dynamic ex = new ExpandoObject ();
ex.Field = "Foobar";
IDictionary<string, object> dict = ex as IDictionary<string, object>;
Console.WriteLine (dict["Field"]);
现在我尝试将它实现到我自己的 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;
}
}
但是编译器将public static implicit operator IDictionary<string, object>
在线失败,并给出错误:“无法转换为接口类型或从接口类型转换”。如果我将隐式运算符更改为 Dictionary,我可以将 MyDynamicObject 转换为 Dictionary 而不会出现任何问题,但不是 IDictionary。
ExpandoObject 如何做到这一点?