類,我有以下的代碼庫:動態初始化實現一個通用接口
public abstract class Business
{
public BusinessType BusinessType { get; set; }
}
public class BusinessA : Business
{
public string SpecialA { get; set; }
}
public class BusinessB : Business
{
public string SpecialB { get; set; }
}
通用接口和類均實現該接口:
public interface IBusinessMapper<T>
{
void DoMapping(T business);
}
public class BusinessMapperA : IBusinessMapper<BusinessA>
{
void DoMapping(BusinessA business)
{
//...
}
}
public class BusinessMapperB : IBusinessMapper<BusinessB>
{
void DoMapping(BusinessB business)
{
//...
}
}
現在我想創建一個實例類BusinessMapperA或BusinessMapperB取決於某些值。是否有可能使用類似這樣的東西?:
public class Core
{
public void Process(Business newBusiness)
{
var mapper = GetBusinessMapper(newBusiness.BusinessType);
mapper.DoMapping();
}
private IBusinessMapper<T> GetBusinessMapper(BusinessType businessType)
{
switch (businessType)
{
case BusinessType.A:
return new BusinessMapperA();
case BusinessType.B:
return new BusinessMapperB();
default:
throw new Exception("Not supported");
}
}
}