2010-12-07 3 views
3

다음 솔루션을 찾으려고 고군분투하는 오버로드 된 생성자가있는 situtation이 있습니다. 중개 할당을 생성자 연결과 함께 사용하는 방법을 볼 수 없습니다.중간 변수로 생성자 체인 연결

다음은 유효하지 않습니다하지만 난

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) 

되어 원하는 것을 보여줍니다 , 컴파일러가 이상하게 작동하지 않는 한 데이터베이스 호출을 두 번 요구한다.

위의 코드를 작성하는 더 좋은 방법이 있습니까?

+0

을 :-) 내 예를 들어 꽤 잘 작동 – VVS

답변

1

예, 있습니다. 나는 example이 Java로되어 있음을 알고 있지만, C#으로 이식하려는 노력이 의미있는 일이라는 것은 좋은 해결책입니다.

2

이것에 대해 무엇 :

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"); 
내가 당신이라면

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 
} 

편집

은이 같은 공장 방법으로 생성자를 대체 할 것

Replace Constructor with Factory Method (refactoring.com)

+0

그것을하지 않습니다. 더 많은 생성자를 추가하기 시작하면 많은 중복 코드가 생성됩니다 (즉, 실제로는 2 개 이상의 생성자 체인이 필요합니다). – fearofawhackplanet

+0

+1 생성자가 복잡해지면 별도의 초기화 논리를 사용하십시오. – VVS

+0

@fearofawhackplanet, 중복 된 코드가 많은 situalition의 예를 들려 줄 수 있습니까? – bniwredyc

1

당신은 정적 도우미 메서드 사용할 수 있습니다 아파요 경우

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

public MyThing(IServiceLocator services, string userName) 
    : this(services, GetUserId(services, userName)) 
{ 
} 

private static int? GetUserId(IServiceLocator services, string userName) 
{ 
    User user = services.UserService.GetUserByName(userName); 
    return (user == null) ? (int?)null : user.Id; 
}