gpt4 book ai didi

asp.net-mvc-2 - MVC 源代码单例模式

转载 作者:行者123 更新时间:2023-12-04 03:33:21 24 4
gpt4 key购买 nike

为什么.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);

第一个的实现使用了 _factoryThunkFunc通过声明 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;
_factoryThunkFunc<IControllerFactory>controllerFactoryIControllerFactory -- 不兼容的类型。

关于asp.net-mvc-2 - MVC 源代码单例模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3856777/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com