我认为我的问题最好用我的类/接口层次结构的代码片段来解释:
public interface ITransform<D> // or <in D> --> seems to make no difference here
{
void Transform(D data);
}
interface ISelection {}
interface IValue : ISelection {}
public interface IEditor : ITransform<IValue> {}
public interface ISelector : IEditor, ITransform<ISelection> {}
class Value : IValue { ... }
class Editor : IEditor { ... } // implements ITransform<IValue>
class Selector : Editor, ISelector { ... } // implements ITransform<ISelection>
Value v = new Value();
Selector s1 = new Selector();
ISelector …Run Code Online (Sandbox Code Playgroud) 我必须根据从服务器收到的一些消息/属性在运行时创建实现,这些消息/属性也需要由新创建的对象进行转换.我是Autofac的新手,但据我所知,有两种方法可以解决这个问题.
方法1:注册专用工厂
...
builder.RegisterType<MTextField>().Keyed<IComponent>(typeof(TextFieldProperties));
builder.RegisterType<ComponentFactory>().As<IComponentFactory>();
public class ComponentFactory : IComponentFactory
{
private readonly IIndex<Type, IComponent> _lookup;
public ComponentFactory(IIndex<Type, IComponent> lookup)
{
_lookup = lookup;
}
public IComponent Create(ComponentProperties properties)
{
var component = _lookup[properties.GetType()];
component.Transform(properties);
return component;
}
}
Run Code Online (Sandbox Code Playgroud)
方法2:根据funcs注册
...
builder.RegisterType<MTextField>().Keyed<IComponent>(typeof(TextFieldProperties));
builder.Register<Func<ComponentProperties, IComponent>>(c =>
{
var context = c.Resolve<IComponentContext>();
return properties =>
{
var component = context.ResolveKeyed<IComponent>(properties.GetType());
component.Transform(properties);
return component;
};
});
Run Code Online (Sandbox Code Playgroud)
问题:
我认为这可能是一个主观的事情,但无论如何我想问.
编辑
好吧,我用autofac玩了一下.这是我目前的做法:
public class TransformerFactory<D, T> : ITransformFactory<D, T>
where T : …Run Code Online (Sandbox Code Playgroud) 我知道这两个库的功能和设计,但我没有找到这两者之间的任何直接性能比较.两者都绝对是很好的库.关于设计,我认为protobuf-csharp-port由于反射较少而应该稍快一点,对吧?
此外:
谢谢.