我想創建一個返回IRowMapper<T>
實例的泛型方法。這裏是我的課:爲什麼要從SomeClass <T>轉換,其中T:BaseClass到SomeClass <DerivedClass:BaseClass>是不可能的?
public abstract class Person
{
public int Id { get; set; }
protected void Person() { }
protected void Person(int id)
{
Id = id;
}
}
public class Employer : Person
{
public int EmployeeId { get; set; }
public void Employer() { }
public void Employer(int id, int employeeId) : base(id)
{
EmployeeId = employeeId;
}
}
public class Employee : Person
{
public int EmployerId { get; set; }
public void Employee() { }
public void Employee(int id, int employerId) : base(id)
{
EmployerId = employerId;
}
}
public static class MapBuilder<TResult> where TResult : new()
{
// ...
}
public interface IRowMapper<TResult>
{
TResult MapRow(IDataRecord row);
}
現在我希望做的是類似如下:
private IRowMapper<T> GetRowMapper<T>() where T : Person, new()
{
var rowMapper = MapBuilder<T>.MapNoProperties()
.Map(c => c.Id).ToColumn("ID");
if (typeof (T) == typeof (Employee))
{
rowMapper =
((MapBuilder<Employee>) rowMapper).Map(c => c.EmployerId)
.ToColumn("EmployerID");
}
else if (typeof (T) == typeof (Employer))
{
rowMapper =
((MapBuilder<Employer>) rowMapper).Map(c => c.EmployeeId)
.ToColumn("EmployeeId");
}
return rowMapper.Build();
}
,但我得到了以下錯誤:
Error 2 Cannot convert type 'Microsoft.Practices.EnterpriseLibrary.Data.IMapBuilderContext' to 'Microsoft.Practices.EnterpriseLibrary.Data.MapBuilder'
Error 2 Cannot convert type 'Microsoft.Practices.EnterpriseLibrary.Data.IMapBuilderContext' to 'Microsoft.Practices.EnterpriseLibrary.Data.MapBuilder'
爲什麼投不可能?
「通用」意味着相同的代碼適用於所有* *類型。針對有限數量的類型使用不同的代碼路徑表明您的設計存在問題。你想達到什麼目的? – dtb 2013-05-08 20:59:26
@dtb,你是對的,使用這樣的東西並不聰明。感謝您的高舉。 – hattenn 2013-05-08 21:07:57