为什么.net MVC源代码ControllerBuilder使用委托(delegate)来分配 Controller 工厂?:
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);
}
最佳答案
原因_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
-- 不兼容的类型。
关于asp.net-mvc-2 - MVC 源代码单例模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3856777/