Source

RubyCSharp / Dynamic / CSharpDynamic / DynamicFeaturesSamples / DynamicEntity.cs

Full commit
using System.Collections.Generic;
using System.Dynamic;
using System;

namespace DynamicFeaturesSamples
{
    public class DynamicEntity : DynamicObject
    {
        readonly Dictionary<string, Func<dynamic, dynamic>> _additionalBehavior;
        Dictionary<string, object> _additionalData = new Dictionary<string, object>();

        public DynamicEntity(Dictionary<string, Func<dynamic, dynamic>> additionalBehavior, Dictionary<string, object> additionalData)
        {
            _additionalBehavior = additionalBehavior;

            foreach (var keyValuePair in additionalData)
            {
                _additionalData.Add(keyValuePair.Key, keyValuePair.Value);
            }
        }

        public override bool TryGetMember(GetMemberBinder binder, out object result)
        {
            if (_additionalData.ContainsKey(binder.Name))
            {
                result = _additionalData[binder.Name];
                return true;
            }
            if (_additionalBehavior.ContainsKey(binder.Name))
            {
                result = _additionalBehavior[binder.Name].Invoke(this);
                return true;
            }
            return base.TryGetMember(binder, out result);
        }

        public override bool TrySetMember(SetMemberBinder binder, object value)
        {
            if (_additionalData.ContainsKey(binder.Name))
            {
                _additionalData[binder.Name] = value;
                return true;
            }

            return base.TrySetMember(binder, value);
        }

        public bool RespondTo(string message)
        {
            return _additionalData.ContainsKey(message) || _additionalBehavior.ContainsKey(message);
        }
    }
}