Skip to content

Instantly share code, notes, and snippets.

@skibitsky
Last active July 28, 2019 14:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save skibitsky/42a72fa7949a36aa60c2f6f3203bb3d5 to your computer and use it in GitHub Desktop.
Save skibitsky/42a72fa7949a36aa60c2f6f3203bb3d5 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Linq;
namespace com.skibitsky.components
{
// Component label interface
public interface IComponent
{
}
public class ComponentsCollection
{
public ComponentsCollection()
{
}
private readonly Dictionary<Type, List<IComponent>> _components = new Dictionary<Type, List<IComponent>>(0);
public void Add<T>(T value) where T: IComponent
{
var type = typeof(T);
if (_components.ContainsKey(type))
_components[type].Add(value);
else
_components[type] = new List<IComponent> {value};
var interfaces = type.GetInterfaces();
foreach (var i in interfaces)
{
if (_components.ContainsKey(i))
_components[i].Add(value);
else
_components[i] = new List<IComponent> {value};
}
}
public void Add(object value)
{
var type = value.GetType();
if (!(value is IComponent)) return;
if (_components.ContainsKey(type))
_components[type].Add((IComponent) value);
else
_components[type] = new List<IComponent> { (IComponent) value};
var interfaces = type.GetInterfaces();
foreach (var i in interfaces)
{
if (_components.ContainsKey(i))
_components[i].Add((IComponent) value);
else
_components[i] = new List<IComponent> { (IComponent) value };
}
}
/// <summary>
/// Returns component by type
/// </summary>
public T GetComponent<T>() where T : IComponent
{
if (!_components.ContainsKey(typeof(T))) return default(T);
return (T)_components[typeof(T)][0];
}
/// <summary>
/// Returns component by reference
/// </summary>
public T GetComponent<T>(T value) where T : IComponent
{
if (!_components.ContainsKey(typeof(T))) return default(T);
if (!_components[typeof(T)].Contains(value)) return default(T);
return (T)_components[typeof(T)].Where(t => t.Equals(value)).ToArray()[0];
}
public T[] GetComponents<T>() where T : IComponent
{
return !_components.ContainsKey(typeof(T)) ? default(T[]) : _components[typeof(T)].Cast<T>().ToArray();
}
public void RemoveComponent<T>(T value) where T : IComponent
{
var type = typeof(T);
if (!_components.ContainsKey(type)) return;
if (_components[type].Contains(value))
_components[type].Remove(value);
if (_components[type].Count == 0)
_components.Remove(type);
var interfaces = type.GetInterfaces();
foreach (var i in interfaces)
{
if (_components.ContainsKey(i))
_components[i].Remove(value);
if (_components[i].Count == 0)
_components.Remove(type);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment