您可以创建一个DynamicObject
,将其接收到的调用转发到一个目标列表中,在责任链样式中(注意多态分派也是这样工作的 - 从最具体的类向上):
public class Composition : DynamicObject {
private List<object> targets = new List<object>();
public Composition(params object[] targets) {
AddTargets(targets);
}
protected void AddTargets(IEnumerable<object> targets) {
this.targets.AddRange(targets);
}
public override bool TryInvokeMember(
InvokeMemberBinder binder, object[] args, out object result) {
foreach (var target in targets) {
var methods = target.GetType().GetMethods();
var targetMethod = methods.FirstOrDefault(m =>
m.Name == binder.Name && ParametersMatch(m, args));
if (targetMethod != null) {
result = targetMethod.Invoke(target, args);
return true;
}
}
return base.TryInvokeMember(binder, args, out result);
}
private bool ParametersMatch(MethodInfo method, object[] args) {
var typesAreTheSame = method.GetParameters().Zip(
args,
(param, arg) => param.GetType() == arg.GetType());
return typesAreTheSame.Count() == args.Length &&
typesAreTheSame.All(_=>_);
}
}
请注意,您还需要实现属性(TryGetMember
和TrySetMember
)、索引器(TryGetIndex
和TrySetIndex
)和操作符(TryBinaryOperation
和TryUnaryOperation
)的委托。
然后,给定一组类:
class MyClass {
public void MyClassMethod() {
Console.WriteLine("MyClass::Method");
}
}
class MyOtherClass {
public void MyOtherClassMethod() {
Console.WriteLine("MyOtherClass::Method");
}
}
你可以将它们全部"混合"在一起:
dynamic blend = new Composition(new MyClass(), new MyOtherClass());
blend.MyClassMethod();
blend.MyOtherClassMethod();
您还可以扩展动态对象,使用类属性或其他类型的注释来查找mixin。例如,给定此注释接口:
public interface Uses<M> where M : new() { }
你可以拥有这个
DynamicObject
:
public class MixinComposition : Composition {
public MixinComposition(object target) :
base(target) {
AddTargets(ResolveMixins(target.GetType()));
}
private IEnumerable<object> ResolveMixins(Type mainType) {
return ResolveMixinTypes(mainType).
Select(m => InstantiateMixin(m));
}
private IEnumerable<Type> ResolveMixinTypes(Type mainType) {
return mainType.GetInterfaces().
Where(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(Uses<>)).
Select(u => u.GetGenericArguments()[0]);
}
private object InstantiateMixin(Type type) {
return Activator.CreateInstance(type);
}
}
就像这样创建你的“混合物”:
class MyMixin {
public void MyMixinMethod() {
Console.WriteLine("MyMixin::Method");
}
}
class MyClass : Uses<MyMixin> {
public void MyClassMethod() {
Console.WriteLine("MyClass::Method");
}
}
...
dynamic blend = new MixinComposition(new MyClass());
blend.MyClassMethod();
blend.MyMixinMethod();