2013-05-08 41 views
1

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

为什么投不可能?

+3

“通用”意味着相同的代码适用于所有* *类型。针对有限数量的类型使用不同的代码路径表明您的设计存在问题。你想达到什么目的? – dtb 2013-05-08 20:59:26

+0

@dtb,你是对的,使用这样的东西并不聪明。感谢您的高举。 – hattenn 2013-05-08 21:07:57

回答

1

我对这个库不太熟悉,但它看起来像每个方法的返回值是IMapBuilderContext<T>,它是用典型的流畅样式编写的。

我认为这可能为你工作:

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 = ((IMapBuilderContextMap<Employee>)rowMapper) 
      .Map(c => c.EmployerId).ToColumn("EmployerID"); 
    } 
    else if (typeof (T) == typeof (Employer)) 
    { 
     rowMapper = ((IMapBuilderContextMap<Employer>)rowMapper) 
      .Map(c => c.EmployeeId).ToColumn("EmployeeId"); 
    } 

    return rowMapper.Build(); 
} 
+0

我还没有尝试过,但我确定它会工作。即使当我复制错误代码时,我也看不到它。非常感谢! – hattenn 2013-05-08 21:05:17

相关问题