I\'ve heard that it\'s possible with extension methods, but I can\'t quite figure it out myself. I\'d like to see a specific example if possible.
Thanks!
If you have a base class that can store data you can enforce compiler safety and use marker interfaces. That's more or less what "Mixins in C# 3.0" from the accepted answer proposes.
public static class ModelBaseMixins
{
public interface IHasStuff{ }
public static void AddStuff(this TObjectBase objectBase, Stuff stuff) where TObjectBase: ObjectBase, IHasStuff
{
var stuffStore = objectBase.Get>("stuffStore");
stuffStore.Add(stuff);
}
}
The ObjectBase:
public abstract class ObjectBase
{
protected ModelBase()
{
_objects = new Dictionary();
}
private readonly Dictionary _objects;
internal void Add(T thing, string name)
{
_objects[name] = thing;
}
internal T Get(string name)
{
T thing = null;
_objects.TryGetValue(name, out thing);
return (T) thing;
}
So if you have a Class you can inherit from 'ObjectBase' and decorate with IHasStuff you can add sutff now