Why can't I index into an ExpandoObject?

前端 未结 2 1703
南方客
南方客 2020-12-11 00:13

Something caught me by surprise when looking into C# dynamics today (I\'ve never used them much, but lately I\'ve been experimenting with the Nancy web framework). I found t

相关标签:
2条回答
  • 2020-12-11 00:42

    how the Expando was able to hide the method of one of its interfaces.

    Because as you correctly found out in the documentation, the indexer is an explicit interface implementation. From Explicit Interface Implementation Tutorial:

    A class that implements an interface can explicitly implement a member of that interface. When a member is explicitly implemented, it cannot be accessed through a class instance, but only through an instance of the interface.

    This means you'll have to cast the reference to the interface to access it:

    ((IDictionary<String, Object>)expando)["name"]
    
    0 讨论(0)
  • 2020-12-11 00:55

    Use this factory class to create ExpandoObjects! Then use HasProperty("prop name") or GetValue("prop name")

    void Main()
    {
        dynamic _obj = ExpandoObjectFactory.Create();
        if (_obj.HasProperty("Foo") == false)
        {
            _obj.Foo = "Foo";
        }
        Console.WriteLine(_obj); // Foo;
        object bar = _obj.GetValue("Bar");
        Console.WriteLine(bar); // null
    }
    
    public static class ExpandoObjectFactory
    {
        public static ExpandoObject Create()
        {
            dynamic expandoObject = new ExpandoObject();
            expandoObject.HasProperty = new Func<string, bool>((string name) => ((IDictionary<string, object>)expandoObject).ContainsKey(name));
            expandoObject.GetValue = new Func<string, object>(delegate (string name)
            {
                ((IDictionary<string, object>)expandoObject).TryGetValue(name, out object value);
                return value;
            });
            return expandoObject;
        }
    }
    
    0 讨论(0)
提交回复
热议问题