2013-05-08 27 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

相關問題