如果您希望将特定类型的参数
Fetch_Data(BaseParameters parameters)
方法,可以将获取参数作为泛型类型引入基类。
public class BusinessLayerBaseNoCSLA<TObject, TParameters>
where TObject : BusinessLayerBaseNoCSLA<TObject, TParameters> // optional
where TParameters : BaseParameters
{
public virtual void Fetch_Data(TParameters parameters)
{
throw new NotWellConfiguredException();
}
}
车辆定义如下:
public class Vehicle : BusinessLayerBaseNoCSLA<Vehicle, GetVehicleParameters>
{
public int VehicleId { get; set; }
public override void Fetch_Data(GetVehicleParameters parameters)
{
//I could cast like var p = (GetVehicleParameters)BaseParameters; here but something smells bad about that
// Note: No need to cast 'parameters' here!
GetVehicleParameters p = parameters;
VehicleId = p.VehicleId;
}
}
public static class DataPortal
{
public static TObject FetchData<TObject, TParameters>(TParameters criteria)
where TObject : BusinessLayerBaseNoCSLA<TObject, TParameters>, new()
where TParameters : BaseParameters
{
var result = new TObject();
//result.Fetch_Data((BaseParameters)criteria);
// Note: no need to cast criteria!
result.Fetch_Data(criteria);
return result;
}
}
用法:
Vehicle vehicle = DataPortal.FetchData<Vehicle, GetVehicleParameters>(new GetVehicleParameters() { VehicleId = 1 });
// Note: we need to explicitly call the FetchData<,> with the correct types