c# - Why casting from SomeClass<T> where T : BaseClass to SomeClass<DerivedClass : BaseClass> is not possible? -
i trying create generic method returns instance of irowmapper<t>
. here classes:
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> tresult : new() { // ... } public interface irowmapper<tresult> { tresult maprow(idatarecord row); }
now following:
private irowmapper<t> getrowmapper<t>() 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(); }
but following error:
error 2 cannot convert type 'microsoft.practices.enterpriselibrary.data.imapbuildercontext' 'microsoft.practices.enterpriselibrary.data.mapbuilder'
error 2 cannot convert type 'microsoft.practices.enterpriselibrary.data.imapbuildercontext' 'microsoft.practices.enterpriselibrary.data.mapbuilder'
why cast not possible?
i'm not familiar library, looks return value of each method imapbuildercontext<t>
, it's written in typical fluent style.
i think might work you:
private irowmapper<t> getrowmapper<t>() 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(); }
Comments
Post a Comment