我想创建一个返回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