为什么从SomeClass <t>进行转换,其中T:BaseClass到SomeClass <derivedclass:=“”baseclass =“”>是不可能的?</derivedclass> </t>

时间:2013-05-08 20:55:46

标签: c# oop generics inheritance covariance

我正在尝试创建一个返回IRowMapper<T>实例的泛型方法。这是我的课程:

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();
}

但是我收到以下错误:

  

错误2无法转换类型   'Microsoft.Practices.EnterpriseLibrary.Data.IMapBuilderContext'到   'Microsoft.Practices.EnterpriseLibrary.Data.MapBuilder'

     

错误2无法转换类型   'Microsoft.Practices.EnterpriseLibrary.Data.IMapBuilderContext'到   'Microsoft.Practices.EnterpriseLibrary.Data.MapBuilder'

为什么演员不可能?

1 个答案:

答案 0 :(得分: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();
}