다음과 같은 상황이 있습니다.유형 매개 변수가있는 일반 공장
My Factory 클래스는 CreateStrategy 함수의 입력 문자열 인수를 기반으로 적절한 Strategy 객체를 만들어야합니다.
Strategy1, Strategy2 등은 모두 공통의 StrategyBase 클래스에서 파생됩니다. 그러나 각 전략에는 Factory 클래스에 대한 유형 매개 변수 인 다른 유효성 검사 메커니즘이 있습니다. 그러나 StrategyValidators는 일반적인 유형이 아니며 인터페이스가 다릅니다.
따라서 아래 코드에서 StrategyValidator 유형에 공통된 제약 조건을 지정할 수 없습니다.
저는 C#에 익숙하지 않아이 디자인 문제를 해결할 수있는 메커니즘이 있는지 확실하지 않습니다. 다음은 사용 목적
Factory f = new Factory();
f.CreateStrategy<WMIValidator>("WMI");
f.CreateStrategy<ABCDValidator>("ABCD");
이야
public class Factory
{
//Create the appropriate Concrete Implementation class based on the type
public static StrategyBase CreateStrategy<StrategyValidator>(String Type)
{
StrategyBase EnumImp = null;
// WMI based implementation
if (Type == "Type1")
{
s = Strategy1<StrategyValidator>.Instance;
}
else if (Type = "Type2")
{
s = Strategy2<StrategyValidator>.Instance;
}
return s;
}
private StrategyBase s;
}
을 제안하십시오 WMIValidator
및 ABCDValidator
는 관련이없는 종류가 있지만 CreateStrategy
기능에 의해 생성 된 실제 클래스 계층 구조 예에 관련된
입력 파라미터로서
유형 'T'를 사용할 수없는 공통베이스 여기서
StrategyBase
를 갖는 문제를 설명하는 샘플 코드
namespace TestCSharp { public interface IStrategy { }; public interface S1 : IStrategy { void f1(); void f2(); }; public class S1Concrete : S1 { public void f1() { } public void f2() { } } public interface S2 : IStrategy { void f3(); void f4(); }; public class S2Concrete : S2 { public void f3() { } public void f4() { } }; public interface ProductBase { }; class Product1<T> : ProductBase where T : S1 { }; class Product2<T> : ProductBase where T : S2 { }; public class Factory { public ProductBase Create<T>(String Type) { if (Type == "P1") return new Product1<T>(); else if (Type == "P2") return new Product2<T>(); } }; class Program { static void Main(string[] args) { Factory f = new Factory(); ProductBase s = f.Create<S1Concrete>("Type1"); } } }
내가 오류은 'T' 제네릭 유형 또는 메소드 'TestCSharp.Product1'. 복싱 변환 또는 'T'에서 'TestCSharp.S1'로의 유형 매개 변수 변환이 없습니다.
의도가 무엇인지 약간 혼란 스럽습니까? 공장을 어떻게 사용하고 싶은지 몇 가지 코드를 추가 할 수 있습니까? –
다른 Strategy 객체와 관련된 다른 유효성 검사 유형을 전달하고 싶습니다.CreateStrategy를 사용하면 사용자 지정 유효성 검사 클래스 – Chubsdad
으로 적절한 Strategy 개체를 인스턴스화하는 데 도움이됩니다. 전략은 동일한 목표를 달성하기 위해 완전히 다른 메커니즘으로 작동하므로 고유성이 있으며 공통성이 없습니다. 일반적으로 – Chubsdad