// ENTITY BASE CLASS
public class Entity {
}
// COMPONENTS (INTERFACES)
public interface ITangibleEntity { }
// COMPONENTS (EXTENSION METHOD IMPLEMENTATIONS)
public static class ComponentExtensions {
private static readonly Dictionary<object, Dictionary<string, object>> adjunctData = new Dictionary<object, Dictionary<string, object>>();
private static T GetAdjunctField<T>(object owningObject, string name) {
return (T) GetDataForObject(owningObject)[name];
}
private static void SetAdjunctField<T>(object owningObject, string name, T value) {
GetDataForObject(owningObject)[name] = value;
}
private static T GetAdjunctField<T>(object owningObject, string name, Func<T> defaultValueGenerator) {
var objectData = GetDataForObject(owningObject);
if (!objectData.ContainsKey(name)) objectData[name] = defaultValueGenerator();
return (T) objectData[name];
}
private static Dictionary<string, object> GetDataForObject(object obj) {
if (!adjunctData.ContainsKey(obj)) adjunctData[obj] = new Dictionary<string, object>();
return adjunctData[obj];
}
// ITangibleEntity
public static Vector3 GetPosition(this ITangibleEntity @this) {
return GetAdjunctField(@this, "ITangibleEntity.Position", () => Vector3.Zero);
}
public static void SetPosition(this ITangibleEntity @this, Vector3 newPosition) {
SetAdjunctField(@this, "ITangibleEntity.Position", newPosition);
}
public static Vector3 GetVelocity(this ITangibleEntity @this) {
return GetAdjunctField(@this, "ITangibleEntity.Velocity", () => Vector3.Zero);
}
public static void SetVelocity(this ITangibleEntity @this, Vector3 newVelocity) {
SetAdjunctField(@this, "ITangibleEntity.Velocity", newVelocity);
}
}
Code snippet taken from "Simulating Multiple Inheritance In C#".