带有中间变量的构造函数链接
我遇到以下带有重载构造函数的情况,我正在努力寻找一个很好的解决方案。我不知道如何使用带有构造函数链接的中间赋值。
以下内容无效,但显示了我想要做的事情
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)
,这不仅是丑陋的代码,而且还需要数据库调用两次(除非编译器足够聪明来工作)出来,我对此表示怀疑)。
上面的内容有更好的写法吗?
I have the following situtation with overloaded constructors which I'm struggling to find a nice solution to. I can't see how to use an intermediate assignment with constructor chaining.
The following isn't valid but shows what I want to do
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);
}
The only way I know to write the above in valid code is
public MyThing(IServiceLocator services, string userName)
: this(services,
services.UserService.GetUserByName(userName) == null ?
null : (int?)services.UserService.GetUserByName(userName).Id)
which is not only ugly code, but also requires the database call twice (unless the compiler is clever enough to work that out, which I doubt).
Is there a better way to write the above?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
怎么样:
编辑
如果我是你,我会用工厂方法替换构造函数,如下所示:
用法:
替换带工厂方法的构造函数(refactoring.com)
What about this:
EDIT
If I were you I'd replace constructor with factory method like this:
Usage:
Replace Constructor with Factory Method (refactoring.com)
有,是的。我知道 示例 是用 Java 编写的,但它是这样的对于您的问题来说,这是一个很好的解决方案,移植到 C# 的一些努力确实有意义。
There is, yes. I know that the example is in Java but it's such a nice solution to your problem that some effort of porting to C# does make sense.
您可以使用静态辅助方法:
You can use a static helper method: