Source

RubyCSharp / Dynamic / CSharpDynamic / DynamicFeaturesSamples / DynamicEntity.cs

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(IEnumerable<KeyValuePair<string, object>> additionalData)
        {
            foreach (var keyValuePair in additionalData)
            {
                _additionalData.Add(keyValuePair.Key, keyValuePair.Value);
            }
        }

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

        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);
        }
    }
}
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.