gpt4 book ai didi

c# - 带有中间变量的构造函数链接

转载 作者:行者123 更新时间:2023-11-30 15:46:22 24 4
gpt4 key购买 nike

我遇到以下重载构造函数的情况,我正在努力寻找一个好的解决方案。我看不出如何使用带有构造函数链的中间赋值。

以下内容无效,但显示了我想做的事情

public MyThing(IServiceLocator services, int? userId)
{
// blah....
}

public MyThing(IServiceLocator services, string userName)
{
User user = services.UserService.GetUserByName(userName);
int userId = user == null ? null : (int?)user.Id;
// call the other constructor
this(services, userId);
}

我知道用有效代码编写上面的唯一方法是

public MyThing(IServiceLocator services, string userName)
: this(services,
services.UserService.GetUserByName(userName) == null ?
null : (int?)services.UserService.GetUserByName(userName).Id)

这不仅是丑陋的代码,而且还需要调用两次数据库(除非编译器足够聪明来解决这个问题,我对此表示怀疑)。

有没有更好的写法?

最佳答案

这个怎么样:

public MyThing(IServiceLocator services, string userName)
{
User user = services.UserService.GetUserByName(userName);
int? userId = user == null ? null : (int?)user.Id;

Initialize(services, userId);
}


public MyThing(IServiceLocator services, int? userId)
{
Initialize(services, userId);
}

private void Initialize(IServiceLocator services, int? userId)
{
// initialization logic
}

编辑

如果我是你,我会用这样的工厂方法替换构造函数:

private MyThing(IServiceLocator services, int? userId)
{
// blah....
}

public static Create(IServiceLocator services, int? userId)
{
return new MyThing(services, userId);
}

public static Create(IServiceLocator services, string userName)
{
User user = services.UserService.GetUserByName(userName);
int userId = user == null ? null : (int?)user.Id;

return new MyThing(services, userId);
}

用法:

var myThing = MyThing.Create(services, 123);
var myOtherThing = MyThing.Create(services, "userName");

Replace Constructor with Factory Method (refactoring.com)

关于c# - 带有中间变量的构造函数链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4376187/

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