C# 모호한 호출 - 다른 반환 유형
-
18-09-2019 - |
문제
MongoDB 문서를 엔티티/객체로 변환하는 2 가지 확장 방법이 있습니다.
public static ProductTemplate Convert(this Document document)
{
return null;
}
public static Product Convert(this Document document)
{
return null;
}
이것은 예상되는 모호한 호출 오류를 제공하므로 어떻게 문제를 해결할 수 있는지 궁금했습니다.
친절한 인사,
피클
해결책
반환 유형으로 기능을 과부하 할 수 없습니다. 당신은 당신의 함수의 이름을 아마도 다음과 같이 바꿔야합니다.
ConvertToproductTemplate () 및 ConvertToproduct ()
또는 공통 기본 클래스 또는 인터페이스를 반환하는 하나의 함수로 바꿉니다. (그러나 발신자는 결과를 얻을 때 캐스트를해야합니다)
다른 팁
당신은 당신을 만들 수 있습니다 Convert
방법 일반 :
public static T ConvertTo<T>(this Document doc) where T : SomeBaseClassOrInterface
{
return null;
}
그런 다음 그렇게 사용하십시오.
var document = new Document();
var temp = document.ConvertTo<ProductTemplate>(); // returns a ProductTemplate
var prod = document.ConvertTo<Product>(); // returns a Product
이름을 변경할 수 있습니다.
public static ProductTemplate ConvertToProductTemplate(this Document document)
{
return null;
}
public static Product ConvertToProduct(this Document document)
{
return null;
}
나는 그 느낌이있다 제품 그리고 ProductTemplate 수업은 어떻게 든 관련이 있습니다 (예 : 제품 확장 ProductTemplate). 내가 옳다면, 당신은 단지 기본 클래스를 반환 할 수 있습니다 (ProductTemplate 이 경우).
Tomas Lycken은 제네릭 방법을 사용하도록 제안했는데, 이는 제 생각에 아주 좋은 생각이지만 제품 및 ProductTemplate에 대한 일반적인 인터페이스가 있다면 해당 인터페이스 대신에도 반환 할 수 있습니다. 제품 그리고 ProductTemplate.
예제 (Tomas Lycken) :
public static T ConvertTo<T>(this Document doc) where T : SomeBaseClassOrInterface
{
return null;
}
예 (나에 의해) :
public static SomeBaseClassOrInterface ConvertTo(this Document doc)
{
return null;
}
그리고 공통 인터페이스가없고 새로운 인터페이스를 만들고 싶지 않다면 이름을 바꾸십시오 :)
제휴하지 않습니다 StackOverflow