Is it possible to implement mixins in C#?

前端 未结 9 629
感动是毒
感动是毒 2020-11-29 17:50

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!

9条回答
  •  误落风尘
    2020-11-29 18:36

    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

提交回复
热议问题