使用中间变量的构造函数链 [英] Constructor chaining with intermediate variables

查看:165
本文介绍了使用中间变量的构造函数链的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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).

推荐答案

这是什么:

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
}

EDIT

如果我是你,我会替换构造函数,这个:

If I were you I'd replace constructor with factory method like this:

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");

使用工厂方法替换构造函数(refactoring.com)

这篇关于使用中间变量的构造函数链的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆