public interface IProvider
{
int Number {get;set;}
}
public class Config
{
public int GetNumber<T>() where T : IProvider
{
// code to find the provider you want
IProvider foundProvider = ProviderFactoryMethodHere(typeof(T));
return foundProvider.Number;
}
}
의 클래스에이 방법 공급자의 모든 클래스는 IProvider 인터페이스를 구현해야하고 당신은 당신이 주어진에 올바른 제공자를 반환하는 공장을 구현해야 일반 메소드에서 요청한 유형.
// Test code example
Config configImpl = new Config();
int numberOfProvider = configImpl.GetNumber<Provider1>();
Assert.Equal(1, numberOfProvider);
간단한 ProviderFactoryMethod 예제를 추가하겠습니다. 형식을 매개 변수로 전달하는 대신이 메서드를 일반화 할 수도 있지만이 예제는 그대로 두겠습니다.
public IProvider ProviderFactoryMethodHere(Type providerRequested)
{
Dictionary <Type, IProvider> providerDict;
if (providerDict == null)
{
// populate dictionary with providers, keyed by their type
providerDict = new Dictionary<Type, IProvider>();
providerDict.Add(typeof(Provider1), new Provider1());
// repeat for all providers, this is pretty simple but definitely works
// we could use other ways of holding on to your provider instances
}
if (providerDict.HasKey(providerRequested))
{
return providerDict[providerRequested];
}
// could throw exception here if you want to use that kind of error
// handling, but we'll just return null for now
return null;
}
건배.
어, 공장은 어떻게 생겼습니까? Btw. GetNumber는 generic 일 수 없습니다 ... 공급자는 문자열 매개 변수로 전달되어야합니다. – Rookian
switch 문을 공장으로 밀어 넣는 것처럼 보입니다. –
@Rookian - "문자열"매핑 값을 의도적으로 제거했습니다. 요구 사항에서 지금까지 설명 된 것처럼 필요하지 않기 때문입니다. 제네릭에 익숙하지 않고 유형을 직접 사용하여 찾고있는 것을 "발견"하는 사람들에게는 매우 일반적입니다. 문제 코드의보다 정교한 사용법은 실제로 문자열이 필요한지 여부를 보여줍니다. 문자열이 어떻게 보이는지 보여주고 문자열이 필요한 이유를 설명 할 수 있습니까? –