Mixins with C# 4.0

后端 未结 5 1588
孤城傲影
孤城傲影 2020-12-13 02:45

I\'ve seen various questions regarding if mixins can be created in C# and they are often directed to the re-mix project on codeplex. However, I don\'t know if I like the \"

5条回答
  •  情深已故
    2020-12-13 02:57

    You can create mixin-like constructs in C# 4.0 without using dynamic, with extension methods on interfaces and the ConditionalWeakTable class to store state. Take a look here for the idea.

    Here's an example:

    public interface MNamed { 
      // required members go here
    }
    public static class MNamedCode {
      // provided methods go here, as extension methods to MNamed
    
      // to maintain state:
      private class State { 
        // public fields or properties for the desired state
        public string Name;
      }
      private static readonly ConditionalWeakTable
        _stateTable = new ConditionalWeakTable();
    
      // to access the state:
      public static string GetName(this MNamed self) {
        return _stateTable.GetOrCreateValue(self).Name;
      }
      public static void SetName(this MNamed self, string value) {
        _stateTable.GetOrCreateValue(self).Name = value;
      }
    }
    

    Use it like this:

    class Order : MNamed { // you can list other mixins here...
      ...
    }
    
    ...
    
    var o = new Order();
    o.SetName("My awesome order");
    
    ...
    
    var name = o.GetName();
    

    The problem of using an attribute is that you can't flow generic parameters from the class to the mixin. You can do this with marker interfaces.

提交回复
热议问题