为什么.net MVC源代码ControllerBuilder使用委托来分配控制器工厂?:
private Func<IControllerFactory> _factoryThunk;
public void SetControllerFactory(IControllerFactory controllerFactory) {
_factoryThunk = () => controllerFactory;
}
为什么不能直接分配ControllerFactory?,即:
private IControllerFactory _factory;
public void SetControllerFactory(IControllerFactory controllerFactory) {
_factory = controllerFactory;
}
public void SetControllerFactory(Type controllerFactoryType) {
_factory = (IControllerFactory)Activator.CreateInstance(controllerFactoryType);
}
答案 0 :(得分:4)
_factoryThunk
当前定义为Func<IControllerFactory>
的原因是它是支持两种重载的通用方法:
void SetControllerFactory(Type);
void SetControllerFactory(IControllerFactory);
第一个的实现使用_factoryThunk
为Func
的事实,通过使用Func
懒惰地Activator
实例化Type
来声明this._factoryThunk = delegate {
IControllerFactory factory;
try
{
factory = (IControllerFactory) Activator.CreateInstance(controllerFactoryType);
}
catch (Exception exception)
{
throw new InvalidOperationException(string.Format(CultureInfo.CurrentUICulture, MvcResources.ControllerBuilder_ErrorCreatingControllerFactory, new object[] { controllerFactoryType }), exception);
}
return factory;
};
内联:
_factoryThunk
因此,其他重载看起来像是虚假实现的原因是,因为Func
被声明为_factoryThunk = controllerFactory;
,所以你建议的行甚至不会被编译:
_factoryThunk
Func<IControllerFactory>
是controllerFactory
而IControllerFactory
是{{1}} - 不兼容的类型。