Why can't I index into an ExpandoObject?

前端 未结 2 1706
南方客
南方客 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: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 name) => ((IDictionary)expandoObject).ContainsKey(name));
            expandoObject.GetValue = new Func(delegate (string name)
            {
                ((IDictionary)expandoObject).TryGetValue(name, out object value);
                return value;
            });
            return expandoObject;
        }
    }
    

提交回复
热议问题